blob: 5cca43b548083934ebd05e4d2a7b0afc1fed954a [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"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Sema/CXXFieldCollector.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000037#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000039#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000040#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000041
42using namespace clang;
43
Chris Lattner8123a952008-04-10 02:22:51 +000044//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
Chris Lattner9e979552008-04-12 23:52:44 +000048namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000054 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000055 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000056 Expr *DefaultArg;
57 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 public:
Mike Stump1eb44332009-09-09 15:08:12 +000060 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000061 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000065 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000066 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000067 };
Chris Lattner8123a952008-04-10 02:22:51 +000068
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitExpr - Visit all of the children of this expression.
70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000072 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000073 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000074 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000075 }
76
Chris Lattner9e979552008-04-12 23:52:44 +000077 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000082 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000091 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000094 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000095 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000098 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000099 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103
Douglas Gregor3996f232008-11-04 13:41:56 +0000104 return false;
105 }
Chris Lattner9e979552008-04-12 23:52:44 +0000106
Douglas Gregor796da182008-11-04 14:32:21 +0000107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000112 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000115 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000116
117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
Chris Lattner8123a952008-04-10 02:22:51 +0000127}
128
Richard Smithe6975e92012-04-17 00:58:00 +0000129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000131 // If we have an MSAny spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000144 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
Richard Smith7a614d82011-06-11 17:19:42 +0000150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
Sean Hunt001cad92011-05-10 00:49:42 +0000153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000197 Exceptions.push_back(*E);
198}
199
Richard Smith7a614d82011-06-11 17:19:42 +0000200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000201 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
Richard Smithe6975e92012-04-17 00:58:00 +0000225 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000226 ComputedEST = EST_None;
227}
228
Anders Carlssoned961f92009-08-25 02:29:20 +0000229bool
John McCall9ae2f072010-08-23 23:25:46 +0000230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000231 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
Anders Carlssoned961f92009-08-25 02:29:20 +0000238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000250 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000251 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000252 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000253
John McCallb4eb64d2010-10-08 02:01:28 +0000254 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000255 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Anders Carlssoned961f92009-08-25 02:29:20 +0000257 // Okay: add the default argument to the parameter
258 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000260 // We have already instantiated this parameter; provide each of the
261 // instantiations with the uninstantiated default argument.
262 UnparsedDefaultArgInstantiationsMap::iterator InstPos
263 = UnparsedDefaultArgInstantiations.find(Param);
264 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268 // We're done tracking this parameter's instantiations.
269 UnparsedDefaultArgInstantiations.erase(InstPos);
270 }
271
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000273}
274
Chris Lattner8123a952008-04-10 02:22:51 +0000275/// ActOnParamDefaultArgument - Check whether the default argument
276/// provided for a function parameter is well-formed. If so, attach it
277/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000278void
John McCalld226f652010-08-21 09:40:31 +0000279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000280 Expr *DefaultArg) {
281 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000282 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
John McCalld226f652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000285 UnparsedDefaultArgLocs.erase(Param);
286
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000288 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000289 Diag(EqualLoc, diag::err_param_default_argument)
290 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000291 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000292 return;
293 }
294
Douglas Gregor6f526752010-12-16 08:48:57 +0000295 // Check for unexpanded parameter packs.
296 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297 Param->setInvalidDecl();
298 return;
299 }
300
Anders Carlsson66e30672009-08-25 01:02:06 +0000301 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000302 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000304 Param->setInvalidDecl();
305 return;
306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307
John McCall9ae2f072010-08-23 23:25:46 +0000308 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309}
310
Douglas Gregor61366e92008-12-24 00:01:03 +0000311/// ActOnParamUnparsedDefaultArgument - We've seen a default
312/// argument for a function parameter, but we can't parse it yet
313/// because we're inside a class definition. Note that this default
314/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000316 SourceLocation EqualLoc,
317 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000318 if (!param)
319 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
John McCalld226f652010-08-21 09:40:31 +0000321 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000322 if (Param)
323 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Anders Carlsson5e300d12009-06-12 16:51:40 +0000325 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000326}
327
Douglas Gregor72b505b2008-12-16 21:30:33 +0000328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000330void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000331 if (!param)
332 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCalld226f652010-08-21 09:40:31 +0000334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000339}
340
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000341/// CheckExtraCXXDefaultArguments - Check for any extra default
342/// arguments in the declarator, which is not a function declaration
343/// or definition and therefore is not permitted to have default
344/// arguments. This routine should be invoked for every declarator
345/// that is not a function declaration or definition.
346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347 // C++ [dcl.fct.default]p3
348 // A default argument expression shall be specified only in the
349 // parameter-declaration-clause of a function declaration or in a
350 // template-parameter (14.1). It shall not be specified for a
351 // parameter pack. If it is specified in a
352 // parameter-declaration-clause, it shall not occur within a
353 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000355 DeclaratorChunk &chunk = D.getTypeObject(i);
356 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000359 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000360 if (Param->hasUnparsedDefaultArg()) {
361 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364 delete Toks;
365 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000366 } else if (Param->getDefaultArg()) {
367 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368 << Param->getDefaultArg()->getSourceRange();
369 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000370 }
371 }
372 }
373 }
374}
375
Craig Topper1a6eac82012-09-21 04:33:26 +0000376/// MergeCXXFunctionDecl - Merge two declarations of the same C++
377/// function, once we already know that they have the same
378/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
379/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000382 bool Invalid = false;
383
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // For non-template functions, default arguments can be added in
386 // later declarations of a function in the same
387 // scope. Declarations in different scopes have completely
388 // distinct sets of default arguments. That is, declarations in
389 // inner scopes do not acquire default arguments from
390 // declarations in outer scopes, and vice versa. In a given
391 // function declaration, all parameters subsequent to a
392 // parameter with a default argument shall have default
393 // arguments supplied in this or previous declarations. A
394 // default argument shall not be redefined by a later
395 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000396 //
397 // C++ [dcl.fct.default]p6:
398 // Except for member functions of class templates, the default arguments
399 // in a member function definition that appears outside of the class
400 // definition are added to the set of default arguments provided by the
401 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403 ParmVarDecl *OldParam = Old->getParamDecl(p);
404 ParmVarDecl *NewParam = New->getParamDecl(p);
405
James Molloy9cda03f2012-03-13 08:55:35 +0000406 bool OldParamHasDfl = OldParam->hasDefaultArg();
407 bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409 NamedDecl *ND = Old;
410 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411 // Ignore default parameters of old decl if they are not in
412 // the same scope.
413 OldParamHasDfl = false;
414
415 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000416
Francois Pichet8d051e02011-04-10 03:03:52 +0000417 unsigned DiagDefaultParamID =
418 diag::err_param_default_argument_redefinition;
419
420 // MSVC accepts that default parameters be redefined for member functions
421 // of template class. The new default parameter's value is ignored.
422 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000423 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000424 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000426 // Merge the old default argument into the new parameter.
427 NewParam->setHasInheritedDefaultArg();
428 if (OldParam->hasUninstantiatedDefaultArg())
429 NewParam->setUninstantiatedDefaultArg(
430 OldParam->getUninstantiatedDefaultArg());
431 else
432 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000433 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000434 Invalid = false;
435 }
436 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000437
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439 // hint here. Alternatively, we could walk the type-source information
440 // for NewParam to find the last source location in the type... but it
441 // isn't worth the effort right now. This is the kind of test case that
442 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000443 // int f(int);
444 // void g(int (*fp)(int) = f);
445 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000447 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000448
449 // Look for the function declaration where the default argument was
450 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000451 for (FunctionDecl *Older = Old->getPreviousDecl();
452 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000453 if (!Older->getParamDecl(p)->hasDefaultArg())
454 break;
455
456 OldParam = Older->getParamDecl(p);
457 }
458
459 Diag(OldParam->getLocation(), diag::note_previous_definition)
460 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000461 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000462 // Merge the old default argument into the new parameter.
463 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000464 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000465 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000466 if (OldParam->hasUninstantiatedDefaultArg())
467 NewParam->setUninstantiatedDefaultArg(
468 OldParam->getUninstantiatedDefaultArg());
469 else
John McCall3d6c1782010-05-04 01:53:42 +0000470 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000471 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000472 if (New->getDescribedFunctionTemplate()) {
473 // Paragraph 4, quoted above, only applies to non-template functions.
474 Diag(NewParam->getLocation(),
475 diag::err_param_default_argument_template_redecl)
476 << NewParam->getDefaultArgRange();
477 Diag(Old->getLocation(), diag::note_template_prev_declaration)
478 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000479 } else if (New->getTemplateSpecializationKind()
480 != TSK_ImplicitInstantiation &&
481 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482 // C++ [temp.expr.spec]p21:
483 // Default function arguments shall not be specified in a declaration
484 // or a definition for one of the following explicit specializations:
485 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000486 // - the explicit specialization of a member function template;
487 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000488 // template where the class template specialization to which the
489 // member function specialization belongs is implicitly
490 // instantiated.
491 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493 << New->getDeclName()
494 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 } else if (New->getDeclContext()->isDependentContext()) {
496 // C++ [dcl.fct.default]p6 (DR217):
497 // Default arguments for a member function of a class template shall
498 // be specified on the initial declaration of the member function
499 // within the class template.
500 //
501 // Reading the tea leaves a bit in DR217 and its reference to DR205
502 // leads me to the conclusion that one cannot add default function
503 // arguments for an out-of-line definition of a member function of a
504 // dependent type.
505 int WhichKind = 2;
506 if (CXXRecordDecl *Record
507 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508 if (Record->getDescribedClassTemplate())
509 WhichKind = 0;
510 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511 WhichKind = 1;
512 else
513 WhichKind = 2;
514 }
515
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_member_template_redecl)
518 << WhichKind
519 << NewParam->getDefaultArgRange();
520 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000521 }
522 }
523
Richard Smithb8abff62012-11-28 03:45:24 +0000524 // DR1344: If a default argument is added outside a class definition and that
525 // default argument makes the function a special member function, the program
526 // is ill-formed. This can only happen for constructors.
527 if (isa<CXXConstructorDecl>(New) &&
528 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
529 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
530 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
531 if (NewSM != OldSM) {
532 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
533 assert(NewParam->hasDefaultArg());
534 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
535 << NewParam->getDefaultArgRange() << NewSM;
536 Diag(Old->getLocation(), diag::note_previous_declaration);
537 }
538 }
539
Richard Smithff234882012-02-20 23:28:05 +0000540 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000541 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000542 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000543 if (New->isConstexpr() != Old->isConstexpr()) {
544 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
545 << New << New->isConstexpr();
546 Diag(Old->getLocation(), diag::note_previous_declaration);
547 Invalid = true;
548 }
549
Douglas Gregore13ad832010-02-12 07:32:17 +0000550 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000551 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000552
Douglas Gregorcda9c672009-02-16 17:45:42 +0000553 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000554}
555
Sebastian Redl60618fa2011-03-12 11:50:43 +0000556/// \brief Merge the exception specifications of two variable declarations.
557///
558/// This is called when there's a redeclaration of a VarDecl. The function
559/// checks if the redeclaration might have an exception specification and
560/// validates compatibility and merges the specs if necessary.
561void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
562 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000563 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000564 return;
565
566 assert(Context.hasSameType(New->getType(), Old->getType()) &&
567 "Should only be called if types are otherwise the same.");
568
569 QualType NewType = New->getType();
570 QualType OldType = Old->getType();
571
572 // We're only interested in pointers and references to functions, as well
573 // as pointers to member functions.
574 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
575 NewType = R->getPointeeType();
576 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
577 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
578 NewType = P->getPointeeType();
579 OldType = OldType->getAs<PointerType>()->getPointeeType();
580 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
581 NewType = M->getPointeeType();
582 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
583 }
584
585 if (!NewType->isFunctionProtoType())
586 return;
587
588 // There's lots of special cases for functions. For function pointers, system
589 // libraries are hopefully not as broken so that we don't need these
590 // workarounds.
591 if (CheckEquivalentExceptionSpec(
592 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
593 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
594 New->setInvalidDecl();
595 }
596}
597
Chris Lattner3d1cee32008-04-08 05:04:30 +0000598/// CheckCXXDefaultArguments - Verify that the default arguments for a
599/// function declaration are well-formed according to C++
600/// [dcl.fct.default].
601void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
602 unsigned NumParams = FD->getNumParams();
603 unsigned p;
604
Douglas Gregorc6889e72012-02-14 22:28:59 +0000605 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
606 isa<CXXMethodDecl>(FD) &&
607 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
608
Chris Lattner3d1cee32008-04-08 05:04:30 +0000609 // Find first parameter with a default argument
610 for (p = 0; p < NumParams; ++p) {
611 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000612 if (Param->hasDefaultArg()) {
613 // C++11 [expr.prim.lambda]p5:
614 // [...] Default arguments (8.3.6) shall not be specified in the
615 // parameter-declaration-clause of a lambda-declarator.
616 //
617 // FIXME: Core issue 974 strikes this sentence, we only provide an
618 // extension warning.
619 if (IsLambda)
620 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
621 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000622 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000623 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000624 }
625
626 // C++ [dcl.fct.default]p4:
627 // In a given function declaration, all parameters
628 // subsequent to a parameter with a default argument shall
629 // have default arguments supplied in this or previous
630 // declarations. A default argument shall not be redefined
631 // by a later declaration (not even to the same value).
632 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000633 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000634 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000635 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000636 if (Param->isInvalidDecl())
637 /* We already complained about this parameter. */;
638 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000639 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000640 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000641 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000642 else
Mike Stump1eb44332009-09-09 15:08:12 +0000643 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000644 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattner3d1cee32008-04-08 05:04:30 +0000646 LastMissingDefaultArg = p;
647 }
648 }
649
650 if (LastMissingDefaultArg > 0) {
651 // Some default arguments were missing. Clear out all of the
652 // default arguments up to (and including) the last missing
653 // default argument, so that we leave the function parameters
654 // in a semantically valid state.
655 for (p = 0; p <= LastMissingDefaultArg; ++p) {
656 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000657 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658 Param->setDefaultArg(0);
659 }
660 }
661 }
662}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000663
Richard Smith9f569cc2011-10-01 02:31:28 +0000664// CheckConstexprParameterTypes - Check whether a function's parameter types
665// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000666// diagnostic and return false.
667static bool CheckConstexprParameterTypes(Sema &SemaRef,
668 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000669 unsigned ArgIndex = 0;
670 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
671 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
672 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
673 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
674 SourceLocation ParamLoc = PD->getLocation();
675 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000676 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000677 diag::err_constexpr_non_literal_param,
678 ArgIndex+1, PD->getSourceRange(),
679 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000680 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 }
Joao Matos17d35c32012-08-31 22:18:20 +0000682 return true;
683}
684
685/// \brief Get diagnostic %select index for tag kind for
686/// record diagnostic message.
687/// WARNING: Indexes apply to particular diagnostics only!
688///
689/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000690static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000691 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000692 case TTK_Struct: return 0;
693 case TTK_Interface: return 1;
694 case TTK_Class: return 2;
695 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000696 }
Joao Matos17d35c32012-08-31 22:18:20 +0000697}
698
699// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
700// the requirements of a constexpr function definition or a constexpr
701// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000702// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000703//
Richard Smith86c3ae42012-02-13 03:54:03 +0000704// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
705bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000706 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
707 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000708 // C++11 [dcl.constexpr]p4:
709 // The definition of a constexpr constructor shall satisfy the following
710 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000711 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000712 const CXXRecordDecl *RD = MD->getParent();
713 if (RD->getNumVBases()) {
714 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
715 << isa<CXXConstructorDecl>(NewFD)
716 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
717 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
718 E = RD->vbases_end(); I != E; ++I)
719 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000720 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 return false;
722 }
Richard Smith35340502012-01-13 04:54:00 +0000723 }
724
725 if (!isa<CXXConstructorDecl>(NewFD)) {
726 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000727 // The definition of a constexpr function shall satisfy the following
728 // constraints:
729 // - it shall not be virtual;
730 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
731 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000732 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000733
Richard Smith86c3ae42012-02-13 03:54:03 +0000734 // If it's not obvious why this function is virtual, find an overridden
735 // function which uses the 'virtual' keyword.
736 const CXXMethodDecl *WrittenVirtual = Method;
737 while (!WrittenVirtual->isVirtualAsWritten())
738 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
739 if (WrittenVirtual != Method)
740 Diag(WrittenVirtual->getLocation(),
741 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 return false;
743 }
744
745 // - its return type shall be a literal type;
746 QualType RT = NewFD->getResultType();
747 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000748 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000749 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000750 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 }
752
Richard Smith35340502012-01-13 04:54:00 +0000753 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000754 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000755 return false;
756
Richard Smith9f569cc2011-10-01 02:31:28 +0000757 return true;
758}
759
760/// Check the given declaration statement is legal within a constexpr function
761/// body. C++0x [dcl.constexpr]p3,p4.
762///
763/// \return true if the body is OK, false if we have diagnosed a problem.
764static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
765 DeclStmt *DS) {
766 // C++0x [dcl.constexpr]p3 and p4:
767 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
768 // contain only
769 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
770 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
771 switch ((*DclIt)->getKind()) {
772 case Decl::StaticAssert:
773 case Decl::Using:
774 case Decl::UsingShadow:
775 case Decl::UsingDirective:
776 case Decl::UnresolvedUsingTypename:
777 // - static_assert-declarations
778 // - using-declarations,
779 // - using-directives,
780 continue;
781
782 case Decl::Typedef:
783 case Decl::TypeAlias: {
784 // - typedef declarations and alias-declarations that do not define
785 // classes or enumerations,
786 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
787 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
788 // Don't allow variably-modified types in constexpr functions.
789 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
790 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
791 << TL.getSourceRange() << TL.getType()
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794 }
795 continue;
796 }
797
798 case Decl::Enum:
799 case Decl::CXXRecord:
800 // As an extension, we allow the declaration (but not the definition) of
801 // classes and enumerations in all declarations, not just in typedef and
802 // alias declarations.
803 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
804 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
805 << isa<CXXConstructorDecl>(Dcl);
806 return false;
807 }
808 continue;
809
810 case Decl::Var:
811 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
812 << isa<CXXConstructorDecl>(Dcl);
813 return false;
814
815 default:
816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
817 << isa<CXXConstructorDecl>(Dcl);
818 return false;
819 }
820 }
821
822 return true;
823}
824
825/// Check that the given field is initialized within a constexpr constructor.
826///
827/// \param Dcl The constexpr constructor being checked.
828/// \param Field The field being checked. This may be a member of an anonymous
829/// struct or union nested within the class being checked.
830/// \param Inits All declarations, including anonymous struct/union members and
831/// indirect members, for which any initialization was provided.
832/// \param Diagnosed Set to true if an error is produced.
833static void CheckConstexprCtorInitializer(Sema &SemaRef,
834 const FunctionDecl *Dcl,
835 FieldDecl *Field,
836 llvm::SmallSet<Decl*, 16> &Inits,
837 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000838 if (Field->isUnnamedBitfield())
839 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000840
841 if (Field->isAnonymousStructOrUnion() &&
842 Field->getType()->getAsCXXRecordDecl()->isEmpty())
843 return;
844
Richard Smith9f569cc2011-10-01 02:31:28 +0000845 if (!Inits.count(Field)) {
846 if (!Diagnosed) {
847 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
848 Diagnosed = true;
849 }
850 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
851 } else if (Field->isAnonymousStructOrUnion()) {
852 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
853 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
854 I != E; ++I)
855 // If an anonymous union contains an anonymous struct of which any member
856 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000857 if (!RD->isUnion() || Inits.count(*I))
858 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000859 }
860}
861
862/// Check the body for the given constexpr function declaration only contains
863/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
864///
865/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000866bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000867 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000868 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000869 // The definition of a constexpr function shall satisfy the following
870 // constraints: [...]
871 // - its function-body shall be = delete, = default, or a
872 // compound-statement
873 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000874 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000875 // In the definition of a constexpr constructor, [...]
876 // - its function-body shall not be a function-try-block;
877 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
878 << isa<CXXConstructorDecl>(Dcl);
879 return false;
880 }
881
882 // - its function-body shall be [...] a compound-statement that contains only
883 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
884
885 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
886 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
887 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
888 switch ((*BodyIt)->getStmtClass()) {
889 case Stmt::NullStmtClass:
890 // - null statements,
891 continue;
892
893 case Stmt::DeclStmtClass:
894 // - static_assert-declarations
895 // - using-declarations,
896 // - using-directives,
897 // - typedef declarations and alias-declarations that do not define
898 // classes or enumerations,
899 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
900 return false;
901 continue;
902
903 case Stmt::ReturnStmtClass:
904 // - and exactly one return statement;
905 if (isa<CXXConstructorDecl>(Dcl))
906 break;
907
908 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000909 continue;
910
911 default:
912 break;
913 }
914
915 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916 << isa<CXXConstructorDecl>(Dcl);
917 return false;
918 }
919
920 if (const CXXConstructorDecl *Constructor
921 = dyn_cast<CXXConstructorDecl>(Dcl)) {
922 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000923 // DR1359:
924 // - every non-variant non-static data member and base class sub-object
925 // shall be initialized;
926 // - if the class is a non-empty union, or for each non-empty anonymous
927 // union member of a non-union class, exactly one non-static data member
928 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000929 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000930 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000931 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
932 return false;
933 }
Richard Smith6e433752011-10-10 16:38:04 +0000934 } else if (!Constructor->isDependentContext() &&
935 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000936 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
937
938 // Skip detailed checking if we have enough initializers, and we would
939 // allow at most one initializer per member.
940 bool AnyAnonStructUnionMembers = false;
941 unsigned Fields = 0;
942 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
943 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000944 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000945 AnyAnonStructUnionMembers = true;
946 break;
947 }
948 }
949 if (AnyAnonStructUnionMembers ||
950 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
951 // Check initialization of non-static data members. Base classes are
952 // always initialized so do not need to be checked. Dependent bases
953 // might not have initializers in the member initializer list.
954 llvm::SmallSet<Decl*, 16> Inits;
955 for (CXXConstructorDecl::init_const_iterator
956 I = Constructor->init_begin(), E = Constructor->init_end();
957 I != E; ++I) {
958 if (FieldDecl *FD = (*I)->getMember())
959 Inits.insert(FD);
960 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
961 Inits.insert(ID->chain_begin(), ID->chain_end());
962 }
963
964 bool Diagnosed = false;
965 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
966 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000967 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000968 if (Diagnosed)
969 return false;
970 }
971 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000972 } else {
973 if (ReturnStmts.empty()) {
974 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
975 return false;
976 }
977 if (ReturnStmts.size() > 1) {
978 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
979 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
980 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
981 return false;
982 }
983 }
984
Richard Smith5ba73e12012-02-04 00:33:54 +0000985 // C++11 [dcl.constexpr]p5:
986 // if no function argument values exist such that the function invocation
987 // substitution would produce a constant expression, the program is
988 // ill-formed; no diagnostic required.
989 // C++11 [dcl.constexpr]p3:
990 // - every constructor call and implicit conversion used in initializing the
991 // return value shall be one of those allowed in a constant expression.
992 // C++11 [dcl.constexpr]p4:
993 // - every constructor involved in initializing non-static data members and
994 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000995 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000996 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000997 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
998 << isa<CXXConstructorDecl>(Dcl);
999 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1000 Diag(Diags[I].first, Diags[I].second);
1001 return false;
1002 }
1003
Richard Smith9f569cc2011-10-01 02:31:28 +00001004 return true;
1005}
1006
Douglas Gregorb48fe382008-10-31 09:07:45 +00001007/// isCurrentClassName - Determine whether the identifier II is the
1008/// name of the class type currently being defined. In the case of
1009/// nested classes, this will only return true if II is the name of
1010/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001011bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1012 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001013 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001014
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001015 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001016 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001017 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001018 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1019 } else
1020 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1021
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001022 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001023 return &II == CurDecl->getIdentifier();
1024 else
1025 return false;
1026}
1027
Douglas Gregor229d47a2012-11-10 07:24:09 +00001028/// \brief Determine whether the given class is a base class of the given
1029/// class, including looking at dependent bases.
1030static bool findCircularInheritance(const CXXRecordDecl *Class,
1031 const CXXRecordDecl *Current) {
1032 SmallVector<const CXXRecordDecl*, 8> Queue;
1033
1034 Class = Class->getCanonicalDecl();
1035 while (true) {
1036 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1037 E = Current->bases_end();
1038 I != E; ++I) {
1039 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1040 if (!Base)
1041 continue;
1042
1043 Base = Base->getDefinition();
1044 if (!Base)
1045 continue;
1046
1047 if (Base->getCanonicalDecl() == Class)
1048 return true;
1049
1050 Queue.push_back(Base);
1051 }
1052
1053 if (Queue.empty())
1054 return false;
1055
1056 Current = Queue.back();
1057 Queue.pop_back();
1058 }
1059
1060 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001061}
1062
Mike Stump1eb44332009-09-09 15:08:12 +00001063/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001064///
1065/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1066/// and returns NULL otherwise.
1067CXXBaseSpecifier *
1068Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1069 SourceRange SpecifierRange,
1070 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001071 TypeSourceInfo *TInfo,
1072 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001073 QualType BaseType = TInfo->getType();
1074
Douglas Gregor2943aed2009-03-03 04:44:36 +00001075 // C++ [class.union]p1:
1076 // A union shall not have base classes.
1077 if (Class->isUnion()) {
1078 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1079 << SpecifierRange;
1080 return 0;
1081 }
1082
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001083 if (EllipsisLoc.isValid() &&
1084 !TInfo->getType()->containsUnexpandedParameterPack()) {
1085 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1086 << TInfo->getTypeLoc().getSourceRange();
1087 EllipsisLoc = SourceLocation();
1088 }
Douglas Gregord777e282012-11-10 01:18:17 +00001089
1090 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1091
1092 if (BaseType->isDependentType()) {
1093 // Make sure that we don't have circular inheritance among our dependent
1094 // bases. For non-dependent bases, the check for completeness below handles
1095 // this.
1096 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1097 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1098 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001099 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001100 Diag(BaseLoc, diag::err_circular_inheritance)
1101 << BaseType << Context.getTypeDeclType(Class);
1102
1103 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1104 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1105 << BaseType;
1106
1107 return 0;
1108 }
1109 }
1110
Mike Stump1eb44332009-09-09 15:08:12 +00001111 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001112 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001113 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001114 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001115
1116 // Base specifiers must be record types.
1117 if (!BaseType->isRecordType()) {
1118 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1119 return 0;
1120 }
1121
1122 // C++ [class.union]p1:
1123 // A union shall not be used as a base class.
1124 if (BaseType->isUnionType()) {
1125 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1126 return 0;
1127 }
1128
1129 // C++ [class.derived]p2:
1130 // The class-name in a base-specifier shall not be an incompletely
1131 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001132 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001133 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001134 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001135 return 0;
John McCall572fc622010-08-17 07:23:57 +00001136 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001137
Eli Friedman1d954f62009-08-15 21:55:26 +00001138 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001139 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001140 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001141 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001143 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1144 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001145
Anders Carlsson1d209272011-03-25 14:55:14 +00001146 // C++ [class]p3:
1147 // If a class is marked final and it appears as a base-type-specifier in
1148 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001149 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001150 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1151 << CXXBaseDecl->getDeclName();
1152 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1153 << CXXBaseDecl->getDeclName();
1154 return 0;
1155 }
1156
John McCall572fc622010-08-17 07:23:57 +00001157 if (BaseDecl->isInvalidDecl())
1158 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001159
1160 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001161 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001162 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001163 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001164}
1165
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001166/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1167/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001168/// example:
1169/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001170/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001171BaseResult
John McCalld226f652010-08-21 09:40:31 +00001172Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001173 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001174 ParsedType basetype, SourceLocation BaseLoc,
1175 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001176 if (!classdecl)
1177 return true;
1178
Douglas Gregor40808ce2009-03-09 23:48:35 +00001179 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001180 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001181 if (!Class)
1182 return true;
1183
Nick Lewycky56062202010-07-26 16:56:01 +00001184 TypeSourceInfo *TInfo = 0;
1185 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001186
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001187 if (EllipsisLoc.isInvalid() &&
1188 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001189 UPPC_BaseType))
1190 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001191
Douglas Gregor2943aed2009-03-03 04:44:36 +00001192 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001193 Virtual, Access, TInfo,
1194 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001195 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001196 else
1197 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregor2943aed2009-03-03 04:44:36 +00001199 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001200}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001201
Douglas Gregor2943aed2009-03-03 04:44:36 +00001202/// \brief Performs the actual work of attaching the given base class
1203/// specifiers to a C++ class.
1204bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1205 unsigned NumBases) {
1206 if (NumBases == 0)
1207 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001208
1209 // Used to keep track of which base types we have already seen, so
1210 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001211 // that the key is always the unqualified canonical type of the base
1212 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001213 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1214
1215 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001216 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001217 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001218 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001219 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001220 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001221 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001222
1223 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1224 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001225 // C++ [class.mi]p3:
1226 // A class shall not be specified as a direct base class of a
1227 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001228 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001229 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001230 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001231 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001232
1233 // Delete the duplicate base class specifier; we're going to
1234 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001235 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001236
1237 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001238 } else {
1239 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001240 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001241 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001242 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1243 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1244 if (Class->isInterface() &&
1245 (!RD->isInterface() ||
1246 KnownBase->getAccessSpecifier() != AS_public)) {
1247 // The Microsoft extension __interface does not permit bases that
1248 // are not themselves public interfaces.
1249 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1250 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1251 << RD->getSourceRange();
1252 Invalid = true;
1253 }
1254 if (RD->hasAttr<WeakAttr>())
1255 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1256 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001257 }
1258 }
1259
1260 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001261 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001262
1263 // Delete the remaining (good) base class specifiers, since their
1264 // data has been copied into the CXXRecordDecl.
1265 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001266 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001267
1268 return Invalid;
1269}
1270
1271/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1272/// class, after checking whether there are any duplicate base
1273/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001274void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001275 unsigned NumBases) {
1276 if (!ClassDecl || !Bases || !NumBases)
1277 return;
1278
1279 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001280 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001281 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001282}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001283
John McCall3cb0ebd2010-03-10 03:28:59 +00001284static CXXRecordDecl *GetClassForType(QualType T) {
1285 if (const RecordType *RT = T->getAs<RecordType>())
1286 return cast<CXXRecordDecl>(RT->getDecl());
1287 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1288 return ICT->getDecl();
1289 else
1290 return 0;
1291}
1292
Douglas Gregora8f32e02009-10-06 17:59:45 +00001293/// \brief Determine whether the type \p Derived is a C++ class that is
1294/// derived from the type \p Base.
1295bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001296 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001297 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001298
1299 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1300 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001301 return false;
1302
John McCall3cb0ebd2010-03-10 03:28:59 +00001303 CXXRecordDecl *BaseRD = GetClassForType(Base);
1304 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001305 return false;
1306
John McCall86ff3082010-02-04 22:26:26 +00001307 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1308 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001309}
1310
1311/// \brief Determine whether the type \p Derived is a C++ class that is
1312/// derived from the type \p Base.
1313bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001314 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001315 return false;
1316
John McCall3cb0ebd2010-03-10 03:28:59 +00001317 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1318 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001319 return false;
1320
John McCall3cb0ebd2010-03-10 03:28:59 +00001321 CXXRecordDecl *BaseRD = GetClassForType(Base);
1322 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323 return false;
1324
Douglas Gregora8f32e02009-10-06 17:59:45 +00001325 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1326}
1327
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001328void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001329 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001330 assert(BasePathArray.empty() && "Base path array must be empty!");
1331 assert(Paths.isRecordingPaths() && "Must record paths!");
1332
1333 const CXXBasePath &Path = Paths.front();
1334
1335 // We first go backward and check if we have a virtual base.
1336 // FIXME: It would be better if CXXBasePath had the base specifier for
1337 // the nearest virtual base.
1338 unsigned Start = 0;
1339 for (unsigned I = Path.size(); I != 0; --I) {
1340 if (Path[I - 1].Base->isVirtual()) {
1341 Start = I - 1;
1342 break;
1343 }
1344 }
1345
1346 // Now add all bases.
1347 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001348 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001349}
1350
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001351/// \brief Determine whether the given base path includes a virtual
1352/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001353bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1354 for (CXXCastPath::const_iterator B = BasePath.begin(),
1355 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001356 B != BEnd; ++B)
1357 if ((*B)->isVirtual())
1358 return true;
1359
1360 return false;
1361}
1362
Douglas Gregora8f32e02009-10-06 17:59:45 +00001363/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1364/// conversion (where Derived and Base are class types) is
1365/// well-formed, meaning that the conversion is unambiguous (and
1366/// that all of the base classes are accessible). Returns true
1367/// and emits a diagnostic if the code is ill-formed, returns false
1368/// otherwise. Loc is the location where this routine should point to
1369/// if there is an error, and Range is the source range to highlight
1370/// if there is an error.
1371bool
1372Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001373 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001374 unsigned AmbigiousBaseConvID,
1375 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001376 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001377 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001378 // First, determine whether the path from Derived to Base is
1379 // ambiguous. This is slightly more expensive than checking whether
1380 // the Derived to Base conversion exists, because here we need to
1381 // explore multiple paths to determine if there is an ambiguity.
1382 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1383 /*DetectVirtual=*/false);
1384 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1385 assert(DerivationOkay &&
1386 "Can only be used with a derived-to-base conversion");
1387 (void)DerivationOkay;
1388
1389 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001390 if (InaccessibleBaseID) {
1391 // Check that the base class can be accessed.
1392 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1393 InaccessibleBaseID)) {
1394 case AR_inaccessible:
1395 return true;
1396 case AR_accessible:
1397 case AR_dependent:
1398 case AR_delayed:
1399 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001400 }
John McCall6b2accb2010-02-10 09:31:12 +00001401 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001402
1403 // Build a base path if necessary.
1404 if (BasePath)
1405 BuildBasePathArray(Paths, *BasePath);
1406 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001407 }
1408
1409 // We know that the derived-to-base conversion is ambiguous, and
1410 // we're going to produce a diagnostic. Perform the derived-to-base
1411 // search just one more time to compute all of the possible paths so
1412 // that we can print them out. This is more expensive than any of
1413 // the previous derived-to-base checks we've done, but at this point
1414 // performance isn't as much of an issue.
1415 Paths.clear();
1416 Paths.setRecordingPaths(true);
1417 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1418 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1419 (void)StillOkay;
1420
1421 // Build up a textual representation of the ambiguous paths, e.g.,
1422 // D -> B -> A, that will be used to illustrate the ambiguous
1423 // conversions in the diagnostic. We only print one of the paths
1424 // to each base class subobject.
1425 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1426
1427 Diag(Loc, AmbigiousBaseConvID)
1428 << Derived << Base << PathDisplayStr << Range << Name;
1429 return true;
1430}
1431
1432bool
1433Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001434 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001435 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001436 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001437 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001438 IgnoreAccess ? 0
1439 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001440 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001441 Loc, Range, DeclarationName(),
1442 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001443}
1444
1445
1446/// @brief Builds a string representing ambiguous paths from a
1447/// specific derived class to different subobjects of the same base
1448/// class.
1449///
1450/// This function builds a string that can be used in error messages
1451/// to show the different paths that one can take through the
1452/// inheritance hierarchy to go from the derived class to different
1453/// subobjects of a base class. The result looks something like this:
1454/// @code
1455/// struct D -> struct B -> struct A
1456/// struct D -> struct C -> struct A
1457/// @endcode
1458std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1459 std::string PathDisplayStr;
1460 std::set<unsigned> DisplayedPaths;
1461 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1462 Path != Paths.end(); ++Path) {
1463 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1464 // We haven't displayed a path to this particular base
1465 // class subobject yet.
1466 PathDisplayStr += "\n ";
1467 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1468 for (CXXBasePath::const_iterator Element = Path->begin();
1469 Element != Path->end(); ++Element)
1470 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1471 }
1472 }
1473
1474 return PathDisplayStr;
1475}
1476
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001477//===----------------------------------------------------------------------===//
1478// C++ class member Handling
1479//===----------------------------------------------------------------------===//
1480
Abramo Bagnara6206d532010-06-05 05:09:32 +00001481/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001482bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1483 SourceLocation ASLoc,
1484 SourceLocation ColonLoc,
1485 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001486 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001487 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001488 ASLoc, ColonLoc);
1489 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001490 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001491}
1492
Richard Smitha4b39652012-08-06 03:25:17 +00001493/// CheckOverrideControl - Check C++11 override control semantics.
1494void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001495 if (D->isInvalidDecl())
1496 return;
1497
Chris Lattner5f9e2722011-07-23 10:55:15 +00001498 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001499
Richard Smitha4b39652012-08-06 03:25:17 +00001500 // Do we know which functions this declaration might be overriding?
1501 bool OverridesAreKnown = !MD ||
1502 (!MD->getParent()->hasAnyDependentBases() &&
1503 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001504
Richard Smitha4b39652012-08-06 03:25:17 +00001505 if (!MD || !MD->isVirtual()) {
1506 if (OverridesAreKnown) {
1507 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1508 Diag(OA->getLocation(),
1509 diag::override_keyword_only_allowed_on_virtual_member_functions)
1510 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1511 D->dropAttr<OverrideAttr>();
1512 }
1513 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1514 Diag(FA->getLocation(),
1515 diag::override_keyword_only_allowed_on_virtual_member_functions)
1516 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1517 D->dropAttr<FinalAttr>();
1518 }
1519 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001520 return;
1521 }
Richard Smitha4b39652012-08-06 03:25:17 +00001522
1523 if (!OverridesAreKnown)
1524 return;
1525
1526 // C++11 [class.virtual]p5:
1527 // If a virtual function is marked with the virt-specifier override and
1528 // does not override a member function of a base class, the program is
1529 // ill-formed.
1530 bool HasOverriddenMethods =
1531 MD->begin_overridden_methods() != MD->end_overridden_methods();
1532 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1533 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1534 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001535}
1536
Richard Smitha4b39652012-08-06 03:25:17 +00001537/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001538/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001539/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001540bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1541 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001542 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001543 return false;
1544
1545 Diag(New->getLocation(), diag::err_final_function_overridden)
1546 << New->getDeclName();
1547 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1548 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001549}
1550
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001551static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001552 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1553 // FIXME: Destruction of ObjC lifetime types has side-effects.
1554 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1555 return !RD->isCompleteDefinition() ||
1556 !RD->hasTrivialDefaultConstructor() ||
1557 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001558 return false;
1559}
1560
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001561/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1562/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001563/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001564/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1565/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001566Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001567Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001568 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001569 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001570 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001571 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001572 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1573 DeclarationName Name = NameInfo.getName();
1574 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001575
1576 // For anonymous bitfields, the location should point to the type.
1577 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001578 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001579
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001580 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001581
John McCall4bde1e12010-06-04 08:34:12 +00001582 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001583 assert(!DS.isFriendSpecified());
1584
Richard Smith1ab0d902011-06-25 02:28:38 +00001585 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001586
John McCalle402e722012-09-25 07:32:39 +00001587 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1588 // The Microsoft extension __interface only permits public member functions
1589 // and prohibits constructors, destructors, operators, non-public member
1590 // functions, static methods and data members.
1591 unsigned InvalidDecl;
1592 bool ShowDeclName = true;
1593 if (!isFunc)
1594 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1595 else if (AS != AS_public)
1596 InvalidDecl = 2;
1597 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1598 InvalidDecl = 3;
1599 else switch (Name.getNameKind()) {
1600 case DeclarationName::CXXConstructorName:
1601 InvalidDecl = 4;
1602 ShowDeclName = false;
1603 break;
1604
1605 case DeclarationName::CXXDestructorName:
1606 InvalidDecl = 5;
1607 ShowDeclName = false;
1608 break;
1609
1610 case DeclarationName::CXXOperatorName:
1611 case DeclarationName::CXXConversionFunctionName:
1612 InvalidDecl = 6;
1613 break;
1614
1615 default:
1616 InvalidDecl = 0;
1617 break;
1618 }
1619
1620 if (InvalidDecl) {
1621 if (ShowDeclName)
1622 Diag(Loc, diag::err_invalid_member_in_interface)
1623 << (InvalidDecl-1) << Name;
1624 else
1625 Diag(Loc, diag::err_invalid_member_in_interface)
1626 << (InvalidDecl-1) << "";
1627 return 0;
1628 }
1629 }
1630
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001631 // C++ 9.2p6: A member shall not be declared to have automatic storage
1632 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001633 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1634 // data members and cannot be applied to names declared const or static,
1635 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001636 switch (DS.getStorageClassSpec()) {
1637 case DeclSpec::SCS_unspecified:
1638 case DeclSpec::SCS_typedef:
1639 case DeclSpec::SCS_static:
1640 // FALL THROUGH.
1641 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001642 case DeclSpec::SCS_mutable:
1643 if (isFunc) {
1644 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001645 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001646 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001647 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Sebastian Redla11f42f2008-11-17 23:24:37 +00001649 // FIXME: It would be nicer if the keyword was ignored only for this
1650 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001651 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001652 }
1653 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001654 default:
1655 if (DS.getStorageClassSpecLoc().isValid())
1656 Diag(DS.getStorageClassSpecLoc(),
1657 diag::err_storageclass_invalid_for_member);
1658 else
1659 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1660 D.getMutableDeclSpec().ClearStorageClassSpecs();
1661 }
1662
Sebastian Redl669d5d72008-11-14 23:42:31 +00001663 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1664 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001665 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001666
1667 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001668 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001669 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001670
1671 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001672 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001673 Diag(Loc, diag::err_bad_variable_name)
1674 << Name;
1675 return 0;
1676 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001677
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001678 IdentifierInfo *II = Name.getAsIdentifierInfo();
1679
Douglas Gregorf2503652011-09-21 14:40:46 +00001680 // Member field could not be with "template" keyword.
1681 // So TemplateParameterLists should be empty in this case.
1682 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001683 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001684 if (TemplateParams->size()) {
1685 // There is no such thing as a member field template.
1686 Diag(D.getIdentifierLoc(), diag::err_template_member)
1687 << II
1688 << SourceRange(TemplateParams->getTemplateLoc(),
1689 TemplateParams->getRAngleLoc());
1690 } else {
1691 // There is an extraneous 'template<>' for this member.
1692 Diag(TemplateParams->getTemplateLoc(),
1693 diag::err_template_member_noparams)
1694 << II
1695 << SourceRange(TemplateParams->getTemplateLoc(),
1696 TemplateParams->getRAngleLoc());
1697 }
1698 return 0;
1699 }
1700
Douglas Gregor922fff22010-10-13 22:19:53 +00001701 if (SS.isSet() && !SS.isInvalid()) {
1702 // The user provided a superfluous scope specifier inside a class
1703 // definition:
1704 //
1705 // class X {
1706 // int X::member;
1707 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001708 if (DeclContext *DC = computeDeclContext(SS, false))
1709 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001710 else
1711 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1712 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001713
Douglas Gregor922fff22010-10-13 22:19:53 +00001714 SS.clear();
1715 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001716
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001717 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001718 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001719 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001720 } else {
Richard Smithca523302012-06-10 03:12:00 +00001721 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001722
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001723 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001724 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001725 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001726 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001727
1728 // Non-instance-fields can't have a bitfield.
1729 if (BitWidth) {
1730 if (Member->isInvalidDecl()) {
1731 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001732 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001733 // C++ 9.6p3: A bit-field shall not be a static member.
1734 // "static member 'A' cannot be a bit-field"
1735 Diag(Loc, diag::err_static_not_bitfield)
1736 << Name << BitWidth->getSourceRange();
1737 } else if (isa<TypedefDecl>(Member)) {
1738 // "typedef member 'x' cannot be a bit-field"
1739 Diag(Loc, diag::err_typedef_not_bitfield)
1740 << Name << BitWidth->getSourceRange();
1741 } else {
1742 // A function typedef ("typedef int f(); f a;").
1743 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1744 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001745 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001746 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001747 }
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Chris Lattner8b963ef2009-03-05 23:01:03 +00001749 BitWidth = 0;
1750 Member->setInvalidDecl();
1751 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001752
1753 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Douglas Gregor37b372b2009-08-20 22:52:58 +00001755 // If we have declared a member function template, set the access of the
1756 // templated declaration as well.
1757 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1758 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001759 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001760
Richard Smitha4b39652012-08-06 03:25:17 +00001761 if (VS.isOverrideSpecified())
1762 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1763 if (VS.isFinalSpecified())
1764 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001765
Douglas Gregorf5251602011-03-08 17:10:18 +00001766 if (VS.getLastLocation().isValid()) {
1767 // Update the end location of a method that has a virt-specifiers.
1768 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1769 MD->setRangeEnd(VS.getLastLocation());
1770 }
Richard Smitha4b39652012-08-06 03:25:17 +00001771
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001772 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001773
Douglas Gregor10bd3682008-11-17 22:58:34 +00001774 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001775
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001776 if (isInstField) {
1777 FieldDecl *FD = cast<FieldDecl>(Member);
1778 FieldCollector->Add(FD);
1779
1780 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1781 FD->getLocation())
1782 != DiagnosticsEngine::Ignored) {
1783 // Remember all explicit private FieldDecls that have a name, no side
1784 // effects and are not part of a dependent type declaration.
1785 if (!FD->isImplicit() && FD->getDeclName() &&
1786 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001787 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001788 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001789 !InitializationHasSideEffects(*FD))
1790 UnusedPrivateFields.insert(FD);
1791 }
1792 }
1793
John McCalld226f652010-08-21 09:40:31 +00001794 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001795}
1796
Hans Wennborg471f9852012-09-18 15:58:06 +00001797namespace {
1798 class UninitializedFieldVisitor
1799 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1800 Sema &S;
1801 ValueDecl *VD;
1802 public:
1803 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1804 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001805 S(S) {
1806 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1807 this->VD = IFD->getAnonField();
1808 else
1809 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001810 }
1811
1812 void HandleExpr(Expr *E) {
1813 if (!E) return;
1814
1815 // Expressions like x(x) sometimes lack the surrounding expressions
1816 // but need to be checked anyways.
1817 HandleValue(E);
1818 Visit(E);
1819 }
1820
1821 void HandleValue(Expr *E) {
1822 E = E->IgnoreParens();
1823
1824 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1825 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001826 return;
1827
1828 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1829 // or union.
1830 MemberExpr *FieldME = ME;
1831
Hans Wennborg471f9852012-09-18 15:58:06 +00001832 Expr *Base = E;
1833 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001834 ME = cast<MemberExpr>(Base);
1835
1836 if (isa<VarDecl>(ME->getMemberDecl()))
1837 return;
1838
1839 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1840 if (!FD->isAnonymousStructOrUnion())
1841 FieldME = ME;
1842
Hans Wennborg471f9852012-09-18 15:58:06 +00001843 Base = ME->getBase();
1844 }
1845
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001846 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001847 unsigned diag = VD->getType()->isReferenceType()
1848 ? diag::warn_reference_field_is_uninit
1849 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001850 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001851 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001852 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001853 }
1854
1855 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1856 HandleValue(CO->getTrueExpr());
1857 HandleValue(CO->getFalseExpr());
1858 return;
1859 }
1860
1861 if (BinaryConditionalOperator *BCO =
1862 dyn_cast<BinaryConditionalOperator>(E)) {
1863 HandleValue(BCO->getCommon());
1864 HandleValue(BCO->getFalseExpr());
1865 return;
1866 }
1867
1868 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1869 switch (BO->getOpcode()) {
1870 default:
1871 return;
1872 case(BO_PtrMemD):
1873 case(BO_PtrMemI):
1874 HandleValue(BO->getLHS());
1875 return;
1876 case(BO_Comma):
1877 HandleValue(BO->getRHS());
1878 return;
1879 }
1880 }
1881 }
1882
1883 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1884 if (E->getCastKind() == CK_LValueToRValue)
1885 HandleValue(E->getSubExpr());
1886
1887 Inherited::VisitImplicitCastExpr(E);
1888 }
1889
1890 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1891 Expr *Callee = E->getCallee();
1892 if (isa<MemberExpr>(Callee))
1893 HandleValue(Callee);
1894
1895 Inherited::VisitCXXMemberCallExpr(E);
1896 }
1897 };
1898 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1899 ValueDecl *VD) {
1900 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1901 }
1902} // namespace
1903
Richard Smith7a614d82011-06-11 17:19:42 +00001904/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001905/// in-class initializer for a non-static C++ class member, and after
1906/// instantiating an in-class initializer in a class template. Such actions
1907/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001908void
Richard Smithca523302012-06-10 03:12:00 +00001909Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001910 Expr *InitExpr) {
1911 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001912 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1913 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001914
1915 if (!InitExpr) {
1916 FD->setInvalidDecl();
1917 FD->removeInClassInitializer();
1918 return;
1919 }
1920
Peter Collingbournefef21892011-10-23 18:59:44 +00001921 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1922 FD->setInvalidDecl();
1923 FD->removeInClassInitializer();
1924 return;
1925 }
1926
Hans Wennborg471f9852012-09-18 15:58:06 +00001927 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1928 != DiagnosticsEngine::Ignored) {
1929 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1930 }
1931
Richard Smith7a614d82011-06-11 17:19:42 +00001932 ExprResult Init = InitExpr;
Douglas Gregordd084272012-09-14 04:20:37 +00001933 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1934 !FD->getDeclContext()->isDependentContext()) {
1935 // Note: We don't type-check when we're in a dependent context, because
1936 // the initialization-substitution code does not properly handle direct
1937 // list initialization. We have the same hackaround for ctor-initializers.
Sebastian Redl772291a2012-02-19 16:31:05 +00001938 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001939 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001940 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1941 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001942 Expr **Inits = &InitExpr;
1943 unsigned NumInits = 1;
1944 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001945 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001946 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001947 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001948 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1949 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001950 if (Init.isInvalid()) {
1951 FD->setInvalidDecl();
1952 return;
1953 }
1954
Richard Smithca523302012-06-10 03:12:00 +00001955 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001956 }
1957
1958 // C++0x [class.base.init]p7:
1959 // The initialization of each base and member constitutes a
1960 // full-expression.
1961 Init = MaybeCreateExprWithCleanups(Init);
1962 if (Init.isInvalid()) {
1963 FD->setInvalidDecl();
1964 return;
1965 }
1966
1967 InitExpr = Init.release();
1968
1969 FD->setInClassInitializer(InitExpr);
1970}
1971
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001972/// \brief Find the direct and/or virtual base specifiers that
1973/// correspond to the given base type, for use in base initialization
1974/// within a constructor.
1975static bool FindBaseInitializer(Sema &SemaRef,
1976 CXXRecordDecl *ClassDecl,
1977 QualType BaseType,
1978 const CXXBaseSpecifier *&DirectBaseSpec,
1979 const CXXBaseSpecifier *&VirtualBaseSpec) {
1980 // First, check for a direct base class.
1981 DirectBaseSpec = 0;
1982 for (CXXRecordDecl::base_class_const_iterator Base
1983 = ClassDecl->bases_begin();
1984 Base != ClassDecl->bases_end(); ++Base) {
1985 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1986 // We found a direct base of this type. That's what we're
1987 // initializing.
1988 DirectBaseSpec = &*Base;
1989 break;
1990 }
1991 }
1992
1993 // Check for a virtual base class.
1994 // FIXME: We might be able to short-circuit this if we know in advance that
1995 // there are no virtual bases.
1996 VirtualBaseSpec = 0;
1997 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1998 // We haven't found a base yet; search the class hierarchy for a
1999 // virtual base class.
2000 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2001 /*DetectVirtual=*/false);
2002 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2003 BaseType, Paths)) {
2004 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2005 Path != Paths.end(); ++Path) {
2006 if (Path->back().Base->isVirtual()) {
2007 VirtualBaseSpec = Path->back().Base;
2008 break;
2009 }
2010 }
2011 }
2012 }
2013
2014 return DirectBaseSpec || VirtualBaseSpec;
2015}
2016
Sebastian Redl6df65482011-09-24 17:48:25 +00002017/// \brief Handle a C++ member initializer using braced-init-list syntax.
2018MemInitResult
2019Sema::ActOnMemInitializer(Decl *ConstructorD,
2020 Scope *S,
2021 CXXScopeSpec &SS,
2022 IdentifierInfo *MemberOrBase,
2023 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002024 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002025 SourceLocation IdLoc,
2026 Expr *InitList,
2027 SourceLocation EllipsisLoc) {
2028 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002029 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002030 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002031}
2032
2033/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002034MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002035Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002036 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002037 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002038 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002039 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002040 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002041 SourceLocation IdLoc,
2042 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002043 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002044 SourceLocation RParenLoc,
2045 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002046 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2047 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002048 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002049 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002050 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002051}
2052
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002053namespace {
2054
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002055// Callback to only accept typo corrections that can be a valid C++ member
2056// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002057class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2058 public:
2059 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2060 : ClassDecl(ClassDecl) {}
2061
2062 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2063 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2064 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2065 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2066 else
2067 return isa<TypeDecl>(ND);
2068 }
2069 return false;
2070 }
2071
2072 private:
2073 CXXRecordDecl *ClassDecl;
2074};
2075
2076}
2077
Sebastian Redl6df65482011-09-24 17:48:25 +00002078/// \brief Handle a C++ member initializer.
2079MemInitResult
2080Sema::BuildMemInitializer(Decl *ConstructorD,
2081 Scope *S,
2082 CXXScopeSpec &SS,
2083 IdentifierInfo *MemberOrBase,
2084 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002085 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002086 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002087 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002088 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002089 if (!ConstructorD)
2090 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002092 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002093
2094 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002095 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002096 if (!Constructor) {
2097 // The user wrote a constructor initializer on a function that is
2098 // not a C++ constructor. Ignore the error for now, because we may
2099 // have more member initializers coming; we'll diagnose it just
2100 // once in ActOnMemInitializers.
2101 return true;
2102 }
2103
2104 CXXRecordDecl *ClassDecl = Constructor->getParent();
2105
2106 // C++ [class.base.init]p2:
2107 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002108 // constructor's class and, if not found in that scope, are looked
2109 // up in the scope containing the constructor's definition.
2110 // [Note: if the constructor's class contains a member with the
2111 // same name as a direct or virtual base class of the class, a
2112 // mem-initializer-id naming the member or base class and composed
2113 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002114 // mem-initializer-id for the hidden base class may be specified
2115 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002116 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002117 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002118 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002119 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00002120 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002121 ValueDecl *Member;
2122 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
2123 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002124 if (EllipsisLoc.isValid())
2125 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002126 << MemberOrBase
2127 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002128
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002129 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002130 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002131 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002132 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002133 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002134 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002135 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002136
2137 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002138 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002139 } else if (DS.getTypeSpecType() == TST_decltype) {
2140 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002141 } else {
2142 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2143 LookupParsedName(R, S, &SS);
2144
2145 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2146 if (!TyD) {
2147 if (R.isAmbiguous()) return true;
2148
John McCallfd225442010-04-09 19:01:14 +00002149 // We don't want access-control diagnostics here.
2150 R.suppressDiagnostics();
2151
Douglas Gregor7a886e12010-01-19 06:46:48 +00002152 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2153 bool NotUnknownSpecialization = false;
2154 DeclContext *DC = computeDeclContext(SS, false);
2155 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2156 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2157
2158 if (!NotUnknownSpecialization) {
2159 // When the scope specifier can refer to a member of an unknown
2160 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002161 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2162 SS.getWithLocInContext(Context),
2163 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002164 if (BaseType.isNull())
2165 return true;
2166
Douglas Gregor7a886e12010-01-19 06:46:48 +00002167 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002168 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002169 }
2170 }
2171
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002172 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002173 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002174 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002175 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002176 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002177 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002178 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2179 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002180 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002181 // We have found a non-static data member with a similar
2182 // name to what was typed; complain and initialize that
2183 // member.
2184 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2185 << MemberOrBase << true << CorrectedQuotedStr
2186 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2187 Diag(Member->getLocation(), diag::note_previous_decl)
2188 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002189
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002190 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002191 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002192 const CXXBaseSpecifier *DirectBaseSpec;
2193 const CXXBaseSpecifier *VirtualBaseSpec;
2194 if (FindBaseInitializer(*this, ClassDecl,
2195 Context.getTypeDeclType(Type),
2196 DirectBaseSpec, VirtualBaseSpec)) {
2197 // We have found a direct or virtual base class with a
2198 // similar name to what was typed; complain and initialize
2199 // that base class.
2200 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002201 << MemberOrBase << false << CorrectedQuotedStr
2202 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002203
2204 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2205 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002206 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002207 diag::note_base_class_specified_here)
2208 << BaseSpec->getType()
2209 << BaseSpec->getSourceRange();
2210
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002211 TyD = Type;
2212 }
2213 }
2214 }
2215
Douglas Gregor7a886e12010-01-19 06:46:48 +00002216 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002217 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002218 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002219 return true;
2220 }
John McCall2b194412009-12-21 10:41:20 +00002221 }
2222
Douglas Gregor7a886e12010-01-19 06:46:48 +00002223 if (BaseType.isNull()) {
2224 BaseType = Context.getTypeDeclType(TyD);
2225 if (SS.isSet()) {
2226 NestedNameSpecifier *Qualifier =
2227 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002228
Douglas Gregor7a886e12010-01-19 06:46:48 +00002229 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002230 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002231 }
John McCall2b194412009-12-21 10:41:20 +00002232 }
2233 }
Mike Stump1eb44332009-09-09 15:08:12 +00002234
John McCalla93c9342009-12-07 02:54:59 +00002235 if (!TInfo)
2236 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002237
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002238 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002239}
2240
Chandler Carruth81c64772011-09-03 01:14:15 +00002241/// Checks a member initializer expression for cases where reference (or
2242/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002243static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2244 Expr *Init,
2245 SourceLocation IdLoc) {
2246 QualType MemberTy = Member->getType();
2247
2248 // We only handle pointers and references currently.
2249 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2250 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2251 return;
2252
2253 const bool IsPointer = MemberTy->isPointerType();
2254 if (IsPointer) {
2255 if (const UnaryOperator *Op
2256 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2257 // The only case we're worried about with pointers requires taking the
2258 // address.
2259 if (Op->getOpcode() != UO_AddrOf)
2260 return;
2261
2262 Init = Op->getSubExpr();
2263 } else {
2264 // We only handle address-of expression initializers for pointers.
2265 return;
2266 }
2267 }
2268
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002269 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2270 // Taking the address of a temporary will be diagnosed as a hard error.
2271 if (IsPointer)
2272 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002273
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002274 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2275 << Member << Init->getSourceRange();
2276 } else if (const DeclRefExpr *DRE
2277 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2278 // We only warn when referring to a non-reference parameter declaration.
2279 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2280 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002281 return;
2282
2283 S.Diag(Init->getExprLoc(),
2284 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2285 : diag::warn_bind_ref_member_to_parameter)
2286 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002287 } else {
2288 // Other initializers are fine.
2289 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002290 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002291
2292 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2293 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002294}
2295
John McCallf312b1e2010-08-26 23:41:50 +00002296MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002297Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002298 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002299 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2300 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2301 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002302 "Member must be a FieldDecl or IndirectFieldDecl");
2303
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002304 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002305 return true;
2306
Douglas Gregor464b2f02010-11-05 22:21:31 +00002307 if (Member->isInvalidDecl())
2308 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002309
John McCallb4190042009-11-04 23:02:40 +00002310 // Diagnose value-uses of fields to initialize themselves, e.g.
2311 // foo(foo)
2312 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002313 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002314 Expr **Args;
2315 unsigned NumArgs;
2316 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2317 Args = ParenList->getExprs();
2318 NumArgs = ParenList->getNumExprs();
2319 } else {
2320 InitListExpr *InitList = cast<InitListExpr>(Init);
2321 Args = InitList->getInits();
2322 NumArgs = InitList->getNumInits();
2323 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002324
Richard Trieude5e75c2012-06-14 23:11:34 +00002325 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2326 != DiagnosticsEngine::Ignored)
2327 for (unsigned i = 0; i < NumArgs; ++i)
2328 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002329 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002330 // initializing the i'th field, throw a warning if any of the >= i'th
2331 // fields are used, as they are not yet initialized.
2332 // Right now we are only handling the case where the i'th field uses
2333 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002334 // Also need to take into account that some fields may be initialized by
2335 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002336 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002337
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002338 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002339
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002341 // Can't check initialization for a member of dependent type or when
2342 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002343 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002344 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002345 bool InitList = false;
2346 if (isa<InitListExpr>(Init)) {
2347 InitList = true;
2348 Args = &Init;
2349 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002350
2351 if (isStdInitializerList(Member->getType(), 0)) {
2352 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2353 << /*at end of ctor*/1 << InitRange;
2354 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002355 }
2356
Chandler Carruth894aed92010-12-06 09:23:57 +00002357 // Initialize the member.
2358 InitializedEntity MemberEntity =
2359 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2360 : InitializedEntity::InitializeMember(IndirectMember, 0);
2361 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002362 InitList ? InitializationKind::CreateDirectList(IdLoc)
2363 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2364 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002365
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2367 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002368 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002369 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002370 if (MemberInit.isInvalid())
2371 return true;
2372
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 CheckImplicitConversions(MemberInit.get(),
2374 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002375
2376 // C++0x [class.base.init]p7:
2377 // The initialization of each base and member constitutes a
2378 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002379 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002380 if (MemberInit.isInvalid())
2381 return true;
2382
2383 // If we are in a dependent context, template instantiation will
2384 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002385 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002386 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2387 // of the information that we have about the member
2388 // initializer. However, deconstructing the ASTs is a dicey process,
2389 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002390 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002391 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002392 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002393 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002394 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2395 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002396 }
2397
Chandler Carruth894aed92010-12-06 09:23:57 +00002398 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002399 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2400 InitRange.getBegin(), Init,
2401 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002402 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002403 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2404 InitRange.getBegin(), Init,
2405 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002406 }
Eli Friedman59c04372009-07-29 19:44:27 +00002407}
2408
John McCallf312b1e2010-08-26 23:41:50 +00002409MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002410Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002411 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002412 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002413 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002414 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002415 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002416 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002417
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002418 bool InitList = true;
2419 Expr **Args = &Init;
2420 unsigned NumArgs = 1;
2421 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2422 InitList = false;
2423 Args = ParenList->getExprs();
2424 NumArgs = ParenList->getNumExprs();
2425 }
2426
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002427 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002428 // Initialize the object.
2429 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2430 QualType(ClassDecl->getTypeForDecl(), 0));
2431 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002432 InitList ? InitializationKind::CreateDirectList(NameLoc)
2433 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2434 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002435 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2436 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002437 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002438 0);
Sean Hunt41717662011-02-26 19:13:13 +00002439 if (DelegationInit.isInvalid())
2440 return true;
2441
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002442 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2443 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002444
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002445 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002446
2447 // C++0x [class.base.init]p7:
2448 // The initialization of each base and member constitutes a
2449 // full-expression.
2450 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2451 if (DelegationInit.isInvalid())
2452 return true;
2453
Eli Friedmand21016f2012-05-19 23:35:23 +00002454 // If we are in a dependent context, template instantiation will
2455 // perform this type-checking again. Just save the arguments that we
2456 // received in a ParenListExpr.
2457 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2458 // of the information that we have about the base
2459 // initializer. However, deconstructing the ASTs is a dicey process,
2460 // and this approach is far more likely to get the corner cases right.
2461 if (CurContext->isDependentContext())
2462 DelegationInit = Owned(Init);
2463
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002464 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002465 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002466 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002467}
2468
2469MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002470Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002471 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002472 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002473 SourceLocation BaseLoc
2474 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002475
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002476 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2477 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2478 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2479
2480 // C++ [class.base.init]p2:
2481 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002482 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002483 // of that class, the mem-initializer is ill-formed. A
2484 // mem-initializer-list can initialize a base class using any
2485 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002486 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002487
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002488 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002489 if (EllipsisLoc.isValid()) {
2490 // This is a pack expansion.
2491 if (!BaseType->containsUnexpandedParameterPack()) {
2492 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002493 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002494
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002495 EllipsisLoc = SourceLocation();
2496 }
2497 } else {
2498 // Check for any unexpanded parameter packs.
2499 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2500 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002501
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002502 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002503 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002504 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002505
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002506 // Check for direct and virtual base classes.
2507 const CXXBaseSpecifier *DirectBaseSpec = 0;
2508 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2509 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002510 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2511 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002512 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002513
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002514 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2515 VirtualBaseSpec);
2516
2517 // C++ [base.class.init]p2:
2518 // Unless the mem-initializer-id names a nonstatic data member of the
2519 // constructor's class or a direct or virtual base of that class, the
2520 // mem-initializer is ill-formed.
2521 if (!DirectBaseSpec && !VirtualBaseSpec) {
2522 // If the class has any dependent bases, then it's possible that
2523 // one of those types will resolve to the same type as
2524 // BaseType. Therefore, just treat this as a dependent base
2525 // class initialization. FIXME: Should we try to check the
2526 // initialization anyway? It seems odd.
2527 if (ClassDecl->hasAnyDependentBases())
2528 Dependent = true;
2529 else
2530 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2531 << BaseType << Context.getTypeDeclType(ClassDecl)
2532 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2533 }
2534 }
2535
2536 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002537 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Sebastian Redl6df65482011-09-24 17:48:25 +00002539 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2540 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002541 InitRange.getBegin(), Init,
2542 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002543 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002544
2545 // C++ [base.class.init]p2:
2546 // If a mem-initializer-id is ambiguous because it designates both
2547 // a direct non-virtual base class and an inherited virtual base
2548 // class, the mem-initializer is ill-formed.
2549 if (DirectBaseSpec && VirtualBaseSpec)
2550 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002551 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002552
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002554 if (!BaseSpec)
2555 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2556
2557 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002558 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002559 Expr **Args = &Init;
2560 unsigned NumArgs = 1;
2561 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002562 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002563 Args = ParenList->getExprs();
2564 NumArgs = ParenList->getNumExprs();
2565 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002566
2567 InitializedEntity BaseEntity =
2568 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2569 InitializationKind Kind =
2570 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2571 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2572 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002573 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2574 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002575 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002576 if (BaseInit.isInvalid())
2577 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002578
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002579 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002580
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002581 // C++0x [class.base.init]p7:
2582 // The initialization of each base and member constitutes a
2583 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002584 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002585 if (BaseInit.isInvalid())
2586 return true;
2587
2588 // If we are in a dependent context, template instantiation will
2589 // perform this type-checking again. Just save the arguments that we
2590 // received in a ParenListExpr.
2591 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2592 // of the information that we have about the base
2593 // initializer. However, deconstructing the ASTs is a dicey process,
2594 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002595 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002596 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002597
Sean Huntcbb67482011-01-08 20:30:50 +00002598 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002599 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002600 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002601 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002602 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002603}
2604
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002605// Create a static_cast\<T&&>(expr).
2606static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2607 QualType ExprType = E->getType();
2608 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2609 SourceLocation ExprLoc = E->getLocStart();
2610 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2611 TargetType, ExprLoc);
2612
2613 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2614 SourceRange(ExprLoc, ExprLoc),
2615 E->getSourceRange()).take();
2616}
2617
Anders Carlssone5ef7402010-04-23 03:10:23 +00002618/// ImplicitInitializerKind - How an implicit base or member initializer should
2619/// initialize its base or member.
2620enum ImplicitInitializerKind {
2621 IIK_Default,
2622 IIK_Copy,
2623 IIK_Move
2624};
2625
Anders Carlssondefefd22010-04-23 02:00:02 +00002626static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002627BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002628 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002629 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002630 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002631 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002632 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002633 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2634 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002635
John McCall60d7b3a2010-08-24 06:29:42 +00002636 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002637
2638 switch (ImplicitInitKind) {
2639 case IIK_Default: {
2640 InitializationKind InitKind
2641 = InitializationKind::CreateDefault(Constructor->getLocation());
2642 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002643 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002644 break;
2645 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002646
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002647 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002648 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002649 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002650 ParmVarDecl *Param = Constructor->getParamDecl(0);
2651 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002652
Anders Carlssone5ef7402010-04-23 03:10:23 +00002653 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002654 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002655 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002656 Constructor->getLocation(), ParamType,
2657 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002658
Eli Friedman5f2987c2012-02-02 03:46:19 +00002659 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2660
Anders Carlssonc7957502010-04-24 22:02:54 +00002661 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002662 QualType ArgTy =
2663 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2664 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002665
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002666 if (Moving) {
2667 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2668 }
2669
John McCallf871d0c2010-08-07 06:22:56 +00002670 CXXCastPath BasePath;
2671 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002672 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2673 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002674 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002675 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002676
Anders Carlssone5ef7402010-04-23 03:10:23 +00002677 InitializationKind InitKind
2678 = InitializationKind::CreateDirect(Constructor->getLocation(),
2679 SourceLocation(), SourceLocation());
2680 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2681 &CopyCtorArg, 1);
2682 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002683 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002684 break;
2685 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002686 }
John McCall9ae2f072010-08-23 23:25:46 +00002687
Douglas Gregor53c374f2010-12-07 00:41:46 +00002688 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002689 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002690 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002691
Anders Carlssondefefd22010-04-23 02:00:02 +00002692 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002693 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002694 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2695 SourceLocation()),
2696 BaseSpec->isVirtual(),
2697 SourceLocation(),
2698 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002699 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002700 SourceLocation());
2701
Anders Carlssondefefd22010-04-23 02:00:02 +00002702 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002703}
2704
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002705static bool RefersToRValueRef(Expr *MemRef) {
2706 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2707 return Referenced->getType()->isRValueReferenceType();
2708}
2709
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002710static bool
2711BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002712 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002713 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002714 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002715 if (Field->isInvalidDecl())
2716 return true;
2717
Chandler Carruthf186b542010-06-29 23:50:44 +00002718 SourceLocation Loc = Constructor->getLocation();
2719
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002720 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2721 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002722 ParmVarDecl *Param = Constructor->getParamDecl(0);
2723 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002724
2725 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002726 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2727 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002728
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002729 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002730 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002731 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002732 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002733
Eli Friedman5f2987c2012-02-02 03:46:19 +00002734 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2735
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002736 if (Moving) {
2737 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2738 }
2739
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002740 // Build a reference to this field within the parameter.
2741 CXXScopeSpec SS;
2742 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2743 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002744 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2745 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002746 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002747 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002748 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002749 ParamType, Loc,
2750 /*IsArrow=*/false,
2751 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002752 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002753 /*FirstQualifierInScope=*/0,
2754 MemberLookup,
2755 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002756 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002757 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002758
2759 // C++11 [class.copy]p15:
2760 // - if a member m has rvalue reference type T&&, it is direct-initialized
2761 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002762 if (RefersToRValueRef(CtorArg.get())) {
2763 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002764 }
2765
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002766 // When the field we are copying is an array, create index variables for
2767 // each dimension of the array. We use these index variables to subscript
2768 // the source array, and other clients (e.g., CodeGen) will perform the
2769 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002770 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002771 QualType BaseType = Field->getType();
2772 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002773 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002774 while (const ConstantArrayType *Array
2775 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002776 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002777 // Create the iteration variable for this array index.
2778 IdentifierInfo *IterationVarName = 0;
2779 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002780 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002781 llvm::raw_svector_ostream OS(Str);
2782 OS << "__i" << IndexVariables.size();
2783 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2784 }
2785 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002786 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002787 IterationVarName, SizeType,
2788 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002789 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002790 IndexVariables.push_back(IterationVar);
2791
2792 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002793 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002794 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002795 assert(!IterationVarRef.isInvalid() &&
2796 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002797 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2798 assert(!IterationVarRef.isInvalid() &&
2799 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002800
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002801 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002802 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002803 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002804 Loc);
2805 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002806 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002807
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002808 BaseType = Array->getElementType();
2809 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002810
2811 // The array subscript expression is an lvalue, which is wrong for moving.
2812 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002813 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002814
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002815 // Construct the entity that we will be initializing. For an array, this
2816 // will be first element in the array, which may require several levels
2817 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002818 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002819 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002820 if (Indirect)
2821 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2822 else
2823 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002824 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2825 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2826 0,
2827 Entities.back()));
2828
2829 // Direct-initialize to use the copy constructor.
2830 InitializationKind InitKind =
2831 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2832
Sebastian Redl74e611a2011-09-04 18:14:28 +00002833 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002834 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002835 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002836
John McCall60d7b3a2010-08-24 06:29:42 +00002837 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002838 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002839 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002840 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002841 if (MemberInit.isInvalid())
2842 return true;
2843
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002844 if (Indirect) {
2845 assert(IndexVariables.size() == 0 &&
2846 "Indirect field improperly initialized");
2847 CXXMemberInit
2848 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2849 Loc, Loc,
2850 MemberInit.takeAs<Expr>(),
2851 Loc);
2852 } else
2853 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2854 Loc, MemberInit.takeAs<Expr>(),
2855 Loc,
2856 IndexVariables.data(),
2857 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002858 return false;
2859 }
2860
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002861 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2862
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002863 QualType FieldBaseElementType =
2864 SemaRef.Context.getBaseElementType(Field->getType());
2865
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002866 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002867 InitializedEntity InitEntity
2868 = Indirect? InitializedEntity::InitializeMember(Indirect)
2869 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002870 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002871 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002872
2873 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002874 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002875 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002876
Douglas Gregor53c374f2010-12-07 00:41:46 +00002877 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002878 if (MemberInit.isInvalid())
2879 return true;
2880
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002881 if (Indirect)
2882 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2883 Indirect, Loc,
2884 Loc,
2885 MemberInit.get(),
2886 Loc);
2887 else
2888 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2889 Field, Loc, Loc,
2890 MemberInit.get(),
2891 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002892 return false;
2893 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002894
Sean Hunt1f2f3842011-05-17 00:19:05 +00002895 if (!Field->getParent()->isUnion()) {
2896 if (FieldBaseElementType->isReferenceType()) {
2897 SemaRef.Diag(Constructor->getLocation(),
2898 diag::err_uninitialized_member_in_ctor)
2899 << (int)Constructor->isImplicit()
2900 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2901 << 0 << Field->getDeclName();
2902 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2903 return true;
2904 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002905
Sean Hunt1f2f3842011-05-17 00:19:05 +00002906 if (FieldBaseElementType.isConstQualified()) {
2907 SemaRef.Diag(Constructor->getLocation(),
2908 diag::err_uninitialized_member_in_ctor)
2909 << (int)Constructor->isImplicit()
2910 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2911 << 1 << Field->getDeclName();
2912 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2913 return true;
2914 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002915 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002916
David Blaikie4e4d0842012-03-11 07:00:24 +00002917 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002918 FieldBaseElementType->isObjCRetainableType() &&
2919 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2920 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002921 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002922 // Default-initialize Objective-C pointers to NULL.
2923 CXXMemberInit
2924 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2925 Loc, Loc,
2926 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2927 Loc);
2928 return false;
2929 }
2930
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002931 // Nothing to initialize.
2932 CXXMemberInit = 0;
2933 return false;
2934}
John McCallf1860e52010-05-20 23:23:51 +00002935
2936namespace {
2937struct BaseAndFieldInfo {
2938 Sema &S;
2939 CXXConstructorDecl *Ctor;
2940 bool AnyErrorsInInits;
2941 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002942 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002943 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002944
2945 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2946 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002947 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2948 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002949 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002950 else if (Generated && Ctor->isMoveConstructor())
2951 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002952 else
2953 IIK = IIK_Default;
2954 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002955
2956 bool isImplicitCopyOrMove() const {
2957 switch (IIK) {
2958 case IIK_Copy:
2959 case IIK_Move:
2960 return true;
2961
2962 case IIK_Default:
2963 return false;
2964 }
David Blaikie30263482012-01-20 21:50:17 +00002965
2966 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002967 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002968
2969 bool addFieldInitializer(CXXCtorInitializer *Init) {
2970 AllToInit.push_back(Init);
2971
2972 // Check whether this initializer makes the field "used".
2973 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2974 S.UnusedPrivateFields.remove(Init->getAnyMember());
2975
2976 return false;
2977 }
John McCallf1860e52010-05-20 23:23:51 +00002978};
2979}
2980
Richard Smitha4950662011-09-19 13:34:43 +00002981/// \brief Determine whether the given indirect field declaration is somewhere
2982/// within an anonymous union.
2983static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2984 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2985 CEnd = F->chain_end();
2986 C != CEnd; ++C)
2987 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2988 if (Record->isUnion())
2989 return true;
2990
2991 return false;
2992}
2993
Douglas Gregorddb21472011-11-02 23:04:16 +00002994/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2995/// array type.
2996static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2997 if (T->isIncompleteArrayType())
2998 return true;
2999
3000 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3001 if (!ArrayT->getSize())
3002 return true;
3003
3004 T = ArrayT->getElementType();
3005 }
3006
3007 return false;
3008}
3009
Richard Smith7a614d82011-06-11 17:19:42 +00003010static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003011 FieldDecl *Field,
3012 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003013
Chandler Carruthe861c602010-06-30 02:59:29 +00003014 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003015 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3016 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003017
Richard Smith0b8220a2012-08-07 21:30:42 +00003018 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003019 // has a brace-or-equal-initializer, the entity is initialized as specified
3020 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003021 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003022 CXXCtorInitializer *Init;
3023 if (Indirect)
3024 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3025 SourceLocation(),
3026 SourceLocation(), 0,
3027 SourceLocation());
3028 else
3029 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3030 SourceLocation(),
3031 SourceLocation(), 0,
3032 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003033 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003034 }
3035
Richard Smithc115f632011-09-18 11:14:50 +00003036 // Don't build an implicit initializer for union members if none was
3037 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003038 if (Field->getParent()->isUnion() ||
3039 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003040 return false;
3041
Douglas Gregorddb21472011-11-02 23:04:16 +00003042 // Don't initialize incomplete or zero-length arrays.
3043 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3044 return false;
3045
John McCallf1860e52010-05-20 23:23:51 +00003046 // Don't try to build an implicit initializer if there were semantic
3047 // errors in any of the initializers (and therefore we might be
3048 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003049 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003050 return false;
3051
Sean Huntcbb67482011-01-08 20:30:50 +00003052 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003053 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3054 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003055 return true;
John McCallf1860e52010-05-20 23:23:51 +00003056
Richard Smith0b8220a2012-08-07 21:30:42 +00003057 if (!Init)
3058 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003059
Richard Smith0b8220a2012-08-07 21:30:42 +00003060 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003061}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003062
3063bool
3064Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3065 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003066 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003067 Constructor->setNumCtorInitializers(1);
3068 CXXCtorInitializer **initializer =
3069 new (Context) CXXCtorInitializer*[1];
3070 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3071 Constructor->setCtorInitializers(initializer);
3072
Sean Huntb76af9c2011-05-03 23:05:34 +00003073 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003074 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003075 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3076 }
3077
Sean Huntc1598702011-05-05 00:05:47 +00003078 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003079
Sean Hunt059ce0d2011-05-01 07:04:31 +00003080 return false;
3081}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003082
John McCallb77115d2011-06-17 00:18:42 +00003083bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3084 CXXCtorInitializer **Initializers,
3085 unsigned NumInitializers,
3086 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003087 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003088 // Just store the initializers as written, they will be checked during
3089 // instantiation.
3090 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003091 Constructor->setNumCtorInitializers(NumInitializers);
3092 CXXCtorInitializer **baseOrMemberInitializers =
3093 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003094 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00003095 NumInitializers * sizeof(CXXCtorInitializer*));
3096 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003097 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003098
3099 // Let template instantiation know whether we had errors.
3100 if (AnyErrors)
3101 Constructor->setInvalidDecl();
3102
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003103 return false;
3104 }
3105
John McCallf1860e52010-05-20 23:23:51 +00003106 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003107
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003108 // We need to build the initializer AST according to order of construction
3109 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003110 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003111 if (!ClassDecl)
3112 return true;
3113
Eli Friedman80c30da2009-11-09 19:20:36 +00003114 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003115
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003116 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003117 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003118
3119 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003120 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003121 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003122 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003123 }
3124
Anders Carlsson711f34a2010-04-21 19:52:01 +00003125 // Keep track of the direct virtual bases.
3126 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3127 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3128 E = ClassDecl->bases_end(); I != E; ++I) {
3129 if (I->isVirtual())
3130 DirectVBases.insert(I);
3131 }
3132
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003133 // Push virtual bases before others.
3134 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3135 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3136
Sean Huntcbb67482011-01-08 20:30:50 +00003137 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003138 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3139 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003140 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003141 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003142 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003143 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003144 VBase, IsInheritedVirtualBase,
3145 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003146 HadError = true;
3147 continue;
3148 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003149
John McCallf1860e52010-05-20 23:23:51 +00003150 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003151 }
3152 }
Mike Stump1eb44332009-09-09 15:08:12 +00003153
John McCallf1860e52010-05-20 23:23:51 +00003154 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003155 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3156 E = ClassDecl->bases_end(); Base != E; ++Base) {
3157 // Virtuals are in the virtual base list and already constructed.
3158 if (Base->isVirtual())
3159 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Sean Huntcbb67482011-01-08 20:30:50 +00003161 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003162 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3163 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003164 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003165 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003166 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003167 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003168 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003169 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003170 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003171 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003172
John McCallf1860e52010-05-20 23:23:51 +00003173 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003174 }
3175 }
Mike Stump1eb44332009-09-09 15:08:12 +00003176
John McCallf1860e52010-05-20 23:23:51 +00003177 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003178 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3179 MemEnd = ClassDecl->decls_end();
3180 Mem != MemEnd; ++Mem) {
3181 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003182 // C++ [class.bit]p2:
3183 // A declaration for a bit-field that omits the identifier declares an
3184 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3185 // initialized.
3186 if (F->isUnnamedBitfield())
3187 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003188
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003189 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003190 // handle anonymous struct/union fields based on their individual
3191 // indirect fields.
3192 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3193 continue;
3194
3195 if (CollectFieldInitializer(*this, Info, F))
3196 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003197 continue;
3198 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003199
3200 // Beyond this point, we only consider default initialization.
3201 if (Info.IIK != IIK_Default)
3202 continue;
3203
3204 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3205 if (F->getType()->isIncompleteArrayType()) {
3206 assert(ClassDecl->hasFlexibleArrayMember() &&
3207 "Incomplete array type is not valid");
3208 continue;
3209 }
3210
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003211 // Initialize each field of an anonymous struct individually.
3212 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3213 HadError = true;
3214
3215 continue;
3216 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003217 }
Mike Stump1eb44332009-09-09 15:08:12 +00003218
John McCallf1860e52010-05-20 23:23:51 +00003219 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003220 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003221 Constructor->setNumCtorInitializers(NumInitializers);
3222 CXXCtorInitializer **baseOrMemberInitializers =
3223 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003224 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003225 NumInitializers * sizeof(CXXCtorInitializer*));
3226 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003227
John McCallef027fe2010-03-16 21:39:52 +00003228 // Constructors implicitly reference the base and member
3229 // destructors.
3230 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3231 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003232 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003233
3234 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003235}
3236
Eli Friedman6347f422009-07-21 19:28:10 +00003237static void *GetKeyForTopLevelField(FieldDecl *Field) {
3238 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003239 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003240 if (RT->getDecl()->isAnonymousStructOrUnion())
3241 return static_cast<void *>(RT->getDecl());
3242 }
3243 return static_cast<void *>(Field);
3244}
3245
Anders Carlssonea356fb2010-04-02 05:42:15 +00003246static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003247 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003248}
3249
Anders Carlssonea356fb2010-04-02 05:42:15 +00003250static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003251 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003252 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003253 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003254
Eli Friedman6347f422009-07-21 19:28:10 +00003255 // For fields injected into the class via declaration of an anonymous union,
3256 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003257 FieldDecl *Field = Member->getAnyMember();
3258
John McCall3c3ccdb2010-04-10 09:28:51 +00003259 // If the field is a member of an anonymous struct or union, our key
3260 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003261 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003262 if (RD->isAnonymousStructOrUnion()) {
3263 while (true) {
3264 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3265 if (Parent->isAnonymousStructOrUnion())
3266 RD = Parent;
3267 else
3268 break;
3269 }
3270
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003271 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003272 }
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003274 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003275}
3276
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003277static void
3278DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003279 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003280 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003281 unsigned NumInits) {
3282 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003283 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003285 // Don't check initializers order unless the warning is enabled at the
3286 // location of at least one initializer.
3287 bool ShouldCheckOrder = false;
3288 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003289 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003290 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3291 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003292 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003293 ShouldCheckOrder = true;
3294 break;
3295 }
3296 }
3297 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003298 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003299
John McCalld6ca8da2010-04-10 07:37:23 +00003300 // Build the list of bases and members in the order that they'll
3301 // actually be initialized. The explicit initializers should be in
3302 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003303 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Anders Carlsson071d6102010-04-02 03:38:04 +00003305 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3306
John McCalld6ca8da2010-04-10 07:37:23 +00003307 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003308 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003309 ClassDecl->vbases_begin(),
3310 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003311 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003312
John McCalld6ca8da2010-04-10 07:37:23 +00003313 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003314 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003315 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003316 if (Base->isVirtual())
3317 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003318 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003319 }
Mike Stump1eb44332009-09-09 15:08:12 +00003320
John McCalld6ca8da2010-04-10 07:37:23 +00003321 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003322 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003323 E = ClassDecl->field_end(); Field != E; ++Field) {
3324 if (Field->isUnnamedBitfield())
3325 continue;
3326
David Blaikie581deb32012-06-06 20:45:41 +00003327 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003328 }
3329
John McCalld6ca8da2010-04-10 07:37:23 +00003330 unsigned NumIdealInits = IdealInitKeys.size();
3331 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003332
Sean Huntcbb67482011-01-08 20:30:50 +00003333 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003334 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003335 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003336 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003337
3338 // Scan forward to try to find this initializer in the idealized
3339 // initializers list.
3340 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3341 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003342 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003343
3344 // If we didn't find this initializer, it must be because we
3345 // scanned past it on a previous iteration. That can only
3346 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003347 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003348 Sema::SemaDiagnosticBuilder D =
3349 SemaRef.Diag(PrevInit->getSourceLocation(),
3350 diag::warn_initializer_out_of_order);
3351
Francois Pichet00eb3f92010-12-04 09:14:42 +00003352 if (PrevInit->isAnyMemberInitializer())
3353 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003354 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003355 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003356
Francois Pichet00eb3f92010-12-04 09:14:42 +00003357 if (Init->isAnyMemberInitializer())
3358 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003359 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003360 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003361
3362 // Move back to the initializer's location in the ideal list.
3363 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3364 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003365 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003366
3367 assert(IdealIndex != NumIdealInits &&
3368 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003369 }
John McCalld6ca8da2010-04-10 07:37:23 +00003370
3371 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003372 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003373}
3374
John McCall3c3ccdb2010-04-10 09:28:51 +00003375namespace {
3376bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003377 CXXCtorInitializer *Init,
3378 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003379 if (!PrevInit) {
3380 PrevInit = Init;
3381 return false;
3382 }
3383
3384 if (FieldDecl *Field = Init->getMember())
3385 S.Diag(Init->getSourceLocation(),
3386 diag::err_multiple_mem_initialization)
3387 << Field->getDeclName()
3388 << Init->getSourceRange();
3389 else {
John McCallf4c73712011-01-19 06:33:43 +00003390 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003391 assert(BaseClass && "neither field nor base");
3392 S.Diag(Init->getSourceLocation(),
3393 diag::err_multiple_base_initialization)
3394 << QualType(BaseClass, 0)
3395 << Init->getSourceRange();
3396 }
3397 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3398 << 0 << PrevInit->getSourceRange();
3399
3400 return true;
3401}
3402
Sean Huntcbb67482011-01-08 20:30:50 +00003403typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003404typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3405
3406bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003407 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003408 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003409 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003410 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003411 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003412
3413 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003414 if (Parent->isUnion()) {
3415 UnionEntry &En = Unions[Parent];
3416 if (En.first && En.first != Child) {
3417 S.Diag(Init->getSourceLocation(),
3418 diag::err_multiple_mem_union_initialization)
3419 << Field->getDeclName()
3420 << Init->getSourceRange();
3421 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3422 << 0 << En.second->getSourceRange();
3423 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003424 }
3425 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003426 En.first = Child;
3427 En.second = Init;
3428 }
David Blaikie6fe29652011-11-17 06:01:57 +00003429 if (!Parent->isAnonymousStructOrUnion())
3430 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003431 }
3432
3433 Child = Parent;
3434 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003435 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003436
3437 return false;
3438}
3439}
3440
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003441/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003442void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003443 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003444 CXXCtorInitializer **meminits,
3445 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003446 bool AnyErrors) {
3447 if (!ConstructorDecl)
3448 return;
3449
3450 AdjustDeclIfTemplate(ConstructorDecl);
3451
3452 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003453 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003454
3455 if (!Constructor) {
3456 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3457 return;
3458 }
3459
Sean Huntcbb67482011-01-08 20:30:50 +00003460 CXXCtorInitializer **MemInits =
3461 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003462
3463 // Mapping for the duplicate initializers check.
3464 // For member initializers, this is keyed with a FieldDecl*.
3465 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003466 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003467
3468 // Mapping for the inconsistent anonymous-union initializers check.
3469 RedundantUnionMap MemberUnions;
3470
Anders Carlssonea356fb2010-04-02 05:42:15 +00003471 bool HadError = false;
3472 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003473 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003474
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003475 // Set the source order index.
3476 Init->setSourceOrder(i);
3477
Francois Pichet00eb3f92010-12-04 09:14:42 +00003478 if (Init->isAnyMemberInitializer()) {
3479 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003480 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3481 CheckRedundantUnionInit(*this, Init, MemberUnions))
3482 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003483 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003484 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3485 if (CheckRedundantInit(*this, Init, Members[Key]))
3486 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003487 } else {
3488 assert(Init->isDelegatingInitializer());
3489 // This must be the only initializer
Richard Smitha6ddea62012-09-14 18:21:10 +00003490 if (NumMemInits != 1) {
3491 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003492 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003493 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003494 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003495 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003496 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003497 // Return immediately as the initializer is set.
3498 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003499 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003500 }
3501
Anders Carlssonea356fb2010-04-02 05:42:15 +00003502 if (HadError)
3503 return;
3504
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003505 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003506
Sean Huntcbb67482011-01-08 20:30:50 +00003507 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003508}
3509
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003510void
John McCallef027fe2010-03-16 21:39:52 +00003511Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3512 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003513 // Ignore dependent contexts. Also ignore unions, since their members never
3514 // have destructors implicitly called.
3515 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003516 return;
John McCall58e6f342010-03-16 05:22:47 +00003517
3518 // FIXME: all the access-control diagnostics are positioned on the
3519 // field/base declaration. That's probably good; that said, the
3520 // user might reasonably want to know why the destructor is being
3521 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003522
Anders Carlsson9f853df2009-11-17 04:44:12 +00003523 // Non-static data members.
3524 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3525 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003526 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003527 if (Field->isInvalidDecl())
3528 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003529
3530 // Don't destroy incomplete or zero-length arrays.
3531 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3532 continue;
3533
Anders Carlsson9f853df2009-11-17 04:44:12 +00003534 QualType FieldType = Context.getBaseElementType(Field->getType());
3535
3536 const RecordType* RT = FieldType->getAs<RecordType>();
3537 if (!RT)
3538 continue;
3539
3540 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003541 if (FieldClassDecl->isInvalidDecl())
3542 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003543 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003544 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003545 // The destructor for an implicit anonymous union member is never invoked.
3546 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3547 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003548
Douglas Gregordb89f282010-07-01 22:47:18 +00003549 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003550 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003551 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003552 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003553 << Field->getDeclName()
3554 << FieldType);
3555
Eli Friedman5f2987c2012-02-02 03:46:19 +00003556 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003557 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003558 }
3559
John McCall58e6f342010-03-16 05:22:47 +00003560 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3561
Anders Carlsson9f853df2009-11-17 04:44:12 +00003562 // Bases.
3563 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3564 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003565 // Bases are always records in a well-formed non-dependent class.
3566 const RecordType *RT = Base->getType()->getAs<RecordType>();
3567
3568 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003569 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003570 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003571
John McCall58e6f342010-03-16 05:22:47 +00003572 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003573 // If our base class is invalid, we probably can't get its dtor anyway.
3574 if (BaseClassDecl->isInvalidDecl())
3575 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003576 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003577 continue;
John McCall58e6f342010-03-16 05:22:47 +00003578
Douglas Gregordb89f282010-07-01 22:47:18 +00003579 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003580 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003581
3582 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003583 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003584 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003585 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003586 << Base->getSourceRange(),
3587 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003588
Eli Friedman5f2987c2012-02-02 03:46:19 +00003589 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003590 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003591 }
3592
3593 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003594 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3595 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003596
3597 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003598 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003599
3600 // Ignore direct virtual bases.
3601 if (DirectVirtualBases.count(RT))
3602 continue;
3603
John McCall58e6f342010-03-16 05:22:47 +00003604 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003605 // If our base class is invalid, we probably can't get its dtor anyway.
3606 if (BaseClassDecl->isInvalidDecl())
3607 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003608 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003609 continue;
John McCall58e6f342010-03-16 05:22:47 +00003610
Douglas Gregordb89f282010-07-01 22:47:18 +00003611 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003612 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003613 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003614 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003615 << VBase->getType(),
3616 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003617
Eli Friedman5f2987c2012-02-02 03:46:19 +00003618 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003619 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003620 }
3621}
3622
John McCalld226f652010-08-21 09:40:31 +00003623void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003624 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003625 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Mike Stump1eb44332009-09-09 15:08:12 +00003627 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003628 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003629 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003630}
3631
Mike Stump1eb44332009-09-09 15:08:12 +00003632bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003633 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003634 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3635 unsigned DiagID;
3636 AbstractDiagSelID SelID;
3637
3638 public:
3639 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3640 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3641
3642 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003643 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003644 if (SelID == -1)
3645 S.Diag(Loc, DiagID) << T;
3646 else
3647 S.Diag(Loc, DiagID) << SelID << T;
3648 }
3649 } Diagnoser(DiagID, SelID);
3650
3651 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003652}
3653
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003654bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003655 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003656 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003657 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Anders Carlsson11f21a02009-03-23 19:10:31 +00003659 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003660 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003661
Ted Kremenek6217b802009-07-29 21:53:49 +00003662 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003663 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003664 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003665 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003667 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003668 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003669 }
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Ted Kremenek6217b802009-07-29 21:53:49 +00003671 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003672 if (!RT)
3673 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003674
John McCall86ff3082010-02-04 22:26:26 +00003675 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003676
John McCall94c3b562010-08-18 09:41:07 +00003677 // We can't answer whether something is abstract until it has a
3678 // definition. If it's currently being defined, we'll walk back
3679 // over all the declarations when we have a full definition.
3680 const CXXRecordDecl *Def = RD->getDefinition();
3681 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003682 return false;
3683
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003684 if (!RD->isAbstract())
3685 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003687 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003688 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003689
John McCall94c3b562010-08-18 09:41:07 +00003690 return true;
3691}
3692
3693void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3694 // Check if we've already emitted the list of pure virtual functions
3695 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003696 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003697 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003698
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003699 CXXFinalOverriderMap FinalOverriders;
3700 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003702 // Keep a set of seen pure methods so we won't diagnose the same method
3703 // more than once.
3704 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3705
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003706 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3707 MEnd = FinalOverriders.end();
3708 M != MEnd;
3709 ++M) {
3710 for (OverridingMethods::iterator SO = M->second.begin(),
3711 SOEnd = M->second.end();
3712 SO != SOEnd; ++SO) {
3713 // C++ [class.abstract]p4:
3714 // A class is abstract if it contains or inherits at least one
3715 // pure virtual function for which the final overrider is pure
3716 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003718 //
3719 if (SO->second.size() != 1)
3720 continue;
3721
3722 if (!SO->second.front().Method->isPure())
3723 continue;
3724
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003725 if (!SeenPureMethods.insert(SO->second.front().Method))
3726 continue;
3727
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003728 Diag(SO->second.front().Method->getLocation(),
3729 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003730 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003731 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003732 }
3733
3734 if (!PureVirtualClassDiagSet)
3735 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3736 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003737}
3738
Anders Carlsson8211eff2009-03-24 01:19:16 +00003739namespace {
John McCall94c3b562010-08-18 09:41:07 +00003740struct AbstractUsageInfo {
3741 Sema &S;
3742 CXXRecordDecl *Record;
3743 CanQualType AbstractType;
3744 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003745
John McCall94c3b562010-08-18 09:41:07 +00003746 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3747 : S(S), Record(Record),
3748 AbstractType(S.Context.getCanonicalType(
3749 S.Context.getTypeDeclType(Record))),
3750 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003751
John McCall94c3b562010-08-18 09:41:07 +00003752 void DiagnoseAbstractType() {
3753 if (Invalid) return;
3754 S.DiagnoseAbstractType(Record);
3755 Invalid = true;
3756 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003757
John McCall94c3b562010-08-18 09:41:07 +00003758 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3759};
3760
3761struct CheckAbstractUsage {
3762 AbstractUsageInfo &Info;
3763 const NamedDecl *Ctx;
3764
3765 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3766 : Info(Info), Ctx(Ctx) {}
3767
3768 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3769 switch (TL.getTypeLocClass()) {
3770#define ABSTRACT_TYPELOC(CLASS, PARENT)
3771#define TYPELOC(CLASS, PARENT) \
3772 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3773#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003774 }
John McCall94c3b562010-08-18 09:41:07 +00003775 }
Mike Stump1eb44332009-09-09 15:08:12 +00003776
John McCall94c3b562010-08-18 09:41:07 +00003777 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3778 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3779 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003780 if (!TL.getArg(I))
3781 continue;
3782
John McCall94c3b562010-08-18 09:41:07 +00003783 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3784 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003785 }
John McCall94c3b562010-08-18 09:41:07 +00003786 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003787
John McCall94c3b562010-08-18 09:41:07 +00003788 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3789 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3790 }
Mike Stump1eb44332009-09-09 15:08:12 +00003791
John McCall94c3b562010-08-18 09:41:07 +00003792 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3793 // Visit the type parameters from a permissive context.
3794 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3795 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3796 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3797 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3798 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3799 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003800 }
John McCall94c3b562010-08-18 09:41:07 +00003801 }
Mike Stump1eb44332009-09-09 15:08:12 +00003802
John McCall94c3b562010-08-18 09:41:07 +00003803 // Visit pointee types from a permissive context.
3804#define CheckPolymorphic(Type) \
3805 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3806 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3807 }
3808 CheckPolymorphic(PointerTypeLoc)
3809 CheckPolymorphic(ReferenceTypeLoc)
3810 CheckPolymorphic(MemberPointerTypeLoc)
3811 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003812 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003813
John McCall94c3b562010-08-18 09:41:07 +00003814 /// Handle all the types we haven't given a more specific
3815 /// implementation for above.
3816 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3817 // Every other kind of type that we haven't called out already
3818 // that has an inner type is either (1) sugar or (2) contains that
3819 // inner type in some way as a subobject.
3820 if (TypeLoc Next = TL.getNextTypeLoc())
3821 return Visit(Next, Sel);
3822
3823 // If there's no inner type and we're in a permissive context,
3824 // don't diagnose.
3825 if (Sel == Sema::AbstractNone) return;
3826
3827 // Check whether the type matches the abstract type.
3828 QualType T = TL.getType();
3829 if (T->isArrayType()) {
3830 Sel = Sema::AbstractArrayType;
3831 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003832 }
John McCall94c3b562010-08-18 09:41:07 +00003833 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3834 if (CT != Info.AbstractType) return;
3835
3836 // It matched; do some magic.
3837 if (Sel == Sema::AbstractArrayType) {
3838 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3839 << T << TL.getSourceRange();
3840 } else {
3841 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3842 << Sel << T << TL.getSourceRange();
3843 }
3844 Info.DiagnoseAbstractType();
3845 }
3846};
3847
3848void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3849 Sema::AbstractDiagSelID Sel) {
3850 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3851}
3852
3853}
3854
3855/// Check for invalid uses of an abstract type in a method declaration.
3856static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3857 CXXMethodDecl *MD) {
3858 // No need to do the check on definitions, which require that
3859 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003860 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003861 return;
3862
3863 // For safety's sake, just ignore it if we don't have type source
3864 // information. This should never happen for non-implicit methods,
3865 // but...
3866 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3867 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3868}
3869
3870/// Check for invalid uses of an abstract type within a class definition.
3871static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3872 CXXRecordDecl *RD) {
3873 for (CXXRecordDecl::decl_iterator
3874 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3875 Decl *D = *I;
3876 if (D->isImplicit()) continue;
3877
3878 // Methods and method templates.
3879 if (isa<CXXMethodDecl>(D)) {
3880 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3881 } else if (isa<FunctionTemplateDecl>(D)) {
3882 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3883 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3884
3885 // Fields and static variables.
3886 } else if (isa<FieldDecl>(D)) {
3887 FieldDecl *FD = cast<FieldDecl>(D);
3888 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3889 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3890 } else if (isa<VarDecl>(D)) {
3891 VarDecl *VD = cast<VarDecl>(D);
3892 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3893 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3894
3895 // Nested classes and class templates.
3896 } else if (isa<CXXRecordDecl>(D)) {
3897 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3898 } else if (isa<ClassTemplateDecl>(D)) {
3899 CheckAbstractClassUsage(Info,
3900 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3901 }
3902 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003903}
3904
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003905/// \brief Perform semantic checks on a class definition that has been
3906/// completing, introducing implicitly-declared members, checking for
3907/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003908void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003909 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003910 return;
3911
John McCall94c3b562010-08-18 09:41:07 +00003912 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3913 AbstractUsageInfo Info(*this, Record);
3914 CheckAbstractClassUsage(Info, Record);
3915 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003916
3917 // If this is not an aggregate type and has no user-declared constructor,
3918 // complain about any non-static data members of reference or const scalar
3919 // type, since they will never get initializers.
3920 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003921 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3922 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003923 bool Complained = false;
3924 for (RecordDecl::field_iterator F = Record->field_begin(),
3925 FEnd = Record->field_end();
3926 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003927 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003928 continue;
3929
Douglas Gregor325e5932010-04-15 00:00:53 +00003930 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003931 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003932 if (!Complained) {
3933 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3934 << Record->getTagKind() << Record;
3935 Complained = true;
3936 }
3937
3938 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3939 << F->getType()->isReferenceType()
3940 << F->getDeclName();
3941 }
3942 }
3943 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003944
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003945 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003946 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003947
3948 if (Record->getIdentifier()) {
3949 // C++ [class.mem]p13:
3950 // If T is the name of a class, then each of the following shall have a
3951 // name different from T:
3952 // - every member of every anonymous union that is a member of class T.
3953 //
3954 // C++ [class.mem]p14:
3955 // In addition, if class T has a user-declared constructor (12.1), every
3956 // non-static data member of class T shall have a name different from T.
3957 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003958 R.first != R.second; ++R.first) {
3959 NamedDecl *D = *R.first;
3960 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3961 isa<IndirectFieldDecl>(D)) {
3962 Diag(D->getLocation(), diag::err_member_name_of_class)
3963 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003964 break;
3965 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003966 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003967 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003968
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003969 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003970 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003971 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003972 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003973 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3974 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3975 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003976
David Blaikieb6b5b972012-09-21 03:21:07 +00003977 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3978 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3979 DiagnoseAbstractType(Record);
3980 }
3981
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003982 // See if a method overloads virtual methods in a base
3983 /// class without overriding any.
3984 if (!Record->isDependentType()) {
3985 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3986 MEnd = Record->method_end();
3987 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003988 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003989 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003990 }
3991 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003992
3993 // Declare inherited constructors. We do this eagerly here because:
3994 // - The standard requires an eager diagnostic for conflicting inherited
3995 // constructors from different classes.
3996 // - The lazy declaration of the other implicit constructors is so as to not
3997 // waste space and performance on classes that are not meant to be
3998 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3999 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004000 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004001}
4002
Richard Smithac713512012-12-08 02:53:02 +00004003void Sema::CheckExplicitlyDefaultedAndDeletedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004004 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
4005 ME = Record->method_end();
Richard Smithac713512012-12-08 02:53:02 +00004006 MI != ME; ++MI) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004007 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00004008 CheckExplicitlyDefaultedSpecialMember(*MI);
Richard Smithac713512012-12-08 02:53:02 +00004009
4010 if (!MI->isImplicit() && !MI->isUserProvided()) {
4011 // For an explicitly defaulted or deleted special member, we defer
4012 // determining triviality until the class is complete. That time is now!
4013 CXXSpecialMember CSM = getSpecialMember(*MI);
4014 if (CSM != CXXInvalid) {
4015 MI->setTrivial(SpecialMemberIsTrivial(*MI, CSM));
4016
4017 // Inform the class that we've finished declaring this member.
4018 Record->finishedDefaultedOrDeletedMember(*MI);
4019 }
4020 }
4021 }
Sean Hunt001cad92011-05-10 00:49:42 +00004022}
4023
Richard Smith7756afa2012-06-10 05:43:50 +00004024/// Is the special member function which would be selected to perform the
4025/// specified operation on the specified class type a constexpr constructor?
4026static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4027 Sema::CXXSpecialMember CSM,
4028 bool ConstArg) {
4029 Sema::SpecialMemberOverloadResult *SMOR =
4030 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4031 false, false, false, false);
4032 if (!SMOR || !SMOR->getMethod())
4033 // A constructor we wouldn't select can't be "involved in initializing"
4034 // anything.
4035 return true;
4036 return SMOR->getMethod()->isConstexpr();
4037}
4038
4039/// Determine whether the specified special member function would be constexpr
4040/// if it were implicitly defined.
4041static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4042 Sema::CXXSpecialMember CSM,
4043 bool ConstArg) {
4044 if (!S.getLangOpts().CPlusPlus0x)
4045 return false;
4046
4047 // C++11 [dcl.constexpr]p4:
4048 // In the definition of a constexpr constructor [...]
4049 switch (CSM) {
4050 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004051 // Since default constructor lookup is essentially trivial (and cannot
4052 // involve, for instance, template instantiation), we compute whether a
4053 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4054 //
4055 // This is important for performance; we need to know whether the default
4056 // constructor is constexpr to determine whether the type is a literal type.
4057 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4058
Richard Smith7756afa2012-06-10 05:43:50 +00004059 case Sema::CXXCopyConstructor:
4060 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004061 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004062 break;
4063
4064 case Sema::CXXCopyAssignment:
4065 case Sema::CXXMoveAssignment:
4066 case Sema::CXXDestructor:
4067 case Sema::CXXInvalid:
4068 return false;
4069 }
4070
4071 // -- if the class is a non-empty union, or for each non-empty anonymous
4072 // union member of a non-union class, exactly one non-static data member
4073 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004074 //
4075 // If we squint, this is guaranteed, since exactly one non-static data member
4076 // will be initialized (if the constructor isn't deleted), we just don't know
4077 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004078 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004079 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004080
4081 // -- the class shall not have any virtual base classes;
4082 if (ClassDecl->getNumVBases())
4083 return false;
4084
4085 // -- every constructor involved in initializing [...] base class
4086 // sub-objects shall be a constexpr constructor;
4087 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4088 BEnd = ClassDecl->bases_end();
4089 B != BEnd; ++B) {
4090 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4091 if (!BaseType) continue;
4092
4093 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4094 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4095 return false;
4096 }
4097
4098 // -- every constructor involved in initializing non-static data members
4099 // [...] shall be a constexpr constructor;
4100 // -- every non-static data member and base class sub-object shall be
4101 // initialized
4102 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4103 FEnd = ClassDecl->field_end();
4104 F != FEnd; ++F) {
4105 if (F->isInvalidDecl())
4106 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004107 if (const RecordType *RecordTy =
4108 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004109 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4110 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4111 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004112 }
4113 }
4114
4115 // All OK, it's constexpr!
4116 return true;
4117}
4118
Richard Smithb9d0b762012-07-27 04:22:15 +00004119static Sema::ImplicitExceptionSpecification
4120computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4121 switch (S.getSpecialMember(MD)) {
4122 case Sema::CXXDefaultConstructor:
4123 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4124 case Sema::CXXCopyConstructor:
4125 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4126 case Sema::CXXCopyAssignment:
4127 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4128 case Sema::CXXMoveConstructor:
4129 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4130 case Sema::CXXMoveAssignment:
4131 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4132 case Sema::CXXDestructor:
4133 return S.ComputeDefaultedDtorExceptionSpec(MD);
4134 case Sema::CXXInvalid:
4135 break;
4136 }
4137 llvm_unreachable("only special members have implicit exception specs");
4138}
4139
Richard Smithdd25e802012-07-30 23:48:14 +00004140static void
4141updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4142 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4143 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4144 ExceptSpec.getEPI(EPI);
4145 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4146 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4147 FPT->getNumArgs(), EPI));
4148 FD->setType(QualType(NewFPT, 0));
4149}
4150
Richard Smithb9d0b762012-07-27 04:22:15 +00004151void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4152 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4153 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4154 return;
4155
Richard Smithdd25e802012-07-30 23:48:14 +00004156 // Evaluate the exception specification.
4157 ImplicitExceptionSpecification ExceptSpec =
4158 computeImplicitExceptionSpec(*this, Loc, MD);
4159
4160 // Update the type of the special member to use it.
4161 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4162
4163 // A user-provided destructor can be defined outside the class. When that
4164 // happens, be sure to update the exception specification on both
4165 // declarations.
4166 const FunctionProtoType *CanonicalFPT =
4167 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4168 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4169 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4170 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004171}
4172
Richard Smith3003e1d2012-05-15 04:39:51 +00004173void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4174 CXXRecordDecl *RD = MD->getParent();
4175 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004176
Richard Smith3003e1d2012-05-15 04:39:51 +00004177 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4178 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004179
4180 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004181 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004182 bool First = MD == MD->getCanonicalDecl();
4183
4184 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004185
4186 // C++11 [dcl.fct.def.default]p1:
4187 // A function that is explicitly defaulted shall
4188 // -- be a special member function (checked elsewhere),
4189 // -- have the same type (except for ref-qualifiers, and except that a
4190 // copy operation can take a non-const reference) as an implicit
4191 // declaration, and
4192 // -- not have default arguments.
4193 unsigned ExpectedParams = 1;
4194 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4195 ExpectedParams = 0;
4196 if (MD->getNumParams() != ExpectedParams) {
4197 // This also checks for default arguments: a copy or move constructor with a
4198 // default argument is classified as a default constructor, and assignment
4199 // operations and destructors can't have default arguments.
4200 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4201 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004202 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004203 } else if (MD->isVariadic()) {
4204 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4205 << CSM << MD->getSourceRange();
4206 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004207 }
4208
Richard Smith3003e1d2012-05-15 04:39:51 +00004209 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004210
Richard Smith7756afa2012-06-10 05:43:50 +00004211 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004212 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004213 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004214 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004215 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004216
Richard Smith3003e1d2012-05-15 04:39:51 +00004217 QualType ReturnType = Context.VoidTy;
4218 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4219 // Check for return type matching.
4220 ReturnType = Type->getResultType();
4221 QualType ExpectedReturnType =
4222 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4223 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4224 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4225 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4226 HadError = true;
4227 }
4228
4229 // A defaulted special member cannot have cv-qualifiers.
4230 if (Type->getTypeQuals()) {
4231 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4232 << (CSM == CXXMoveAssignment);
4233 HadError = true;
4234 }
4235 }
4236
4237 // Check for parameter type matching.
4238 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004239 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004240 if (ExpectedParams && ArgType->isReferenceType()) {
4241 // Argument must be reference to possibly-const T.
4242 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004243 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004244
4245 if (ReferentType.isVolatileQualified()) {
4246 Diag(MD->getLocation(),
4247 diag::err_defaulted_special_member_volatile_param) << CSM;
4248 HadError = true;
4249 }
4250
Richard Smith7756afa2012-06-10 05:43:50 +00004251 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004252 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4253 Diag(MD->getLocation(),
4254 diag::err_defaulted_special_member_copy_const_param)
4255 << (CSM == CXXCopyAssignment);
4256 // FIXME: Explain why this special member can't be const.
4257 } else {
4258 Diag(MD->getLocation(),
4259 diag::err_defaulted_special_member_move_const_param)
4260 << (CSM == CXXMoveAssignment);
4261 }
4262 HadError = true;
4263 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004264 } else if (ExpectedParams) {
4265 // A copy assignment operator can take its argument by value, but a
4266 // defaulted one cannot.
4267 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004268 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004269 HadError = true;
4270 }
Sean Huntbe631222011-05-17 20:44:43 +00004271
Richard Smithb9d0b762012-07-27 04:22:15 +00004272 // Rebuild the type with the implicit exception specification added, if we
4273 // are going to need it.
4274 const FunctionProtoType *ImplicitType = 0;
4275 if (First || Type->hasExceptionSpec()) {
4276 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4277 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4278 ImplicitType = cast<FunctionProtoType>(
4279 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4280 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004281
Richard Smith61802452011-12-22 02:22:31 +00004282 // C++11 [dcl.fct.def.default]p2:
4283 // An explicitly-defaulted function may be declared constexpr only if it
4284 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004285 // Do not apply this rule to members of class templates, since core issue 1358
4286 // makes such functions always instantiate to constexpr functions. For
4287 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004288 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4289 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004290 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4291 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4292 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004293 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004294 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004295 }
4296 // and may have an explicit exception-specification only if it is compatible
4297 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004298 if (Type->hasExceptionSpec() &&
4299 CheckEquivalentExceptionSpec(
4300 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4301 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4302 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004303
4304 // If a function is explicitly defaulted on its first declaration,
4305 if (First) {
4306 // -- it is implicitly considered to be constexpr if the implicit
4307 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004308 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004309
Richard Smith3003e1d2012-05-15 04:39:51 +00004310 // -- it is implicitly considered to have the same exception-specification
4311 // as if it had been implicitly declared,
4312 MD->setType(QualType(ImplicitType, 0));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004313 }
4314
Richard Smith3003e1d2012-05-15 04:39:51 +00004315 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004316 if (First) {
4317 MD->setDeletedAsWritten();
4318 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004319 // C++11 [dcl.fct.def.default]p4:
4320 // [For a] user-provided explicitly-defaulted function [...] if such a
4321 // function is implicitly defined as deleted, the program is ill-formed.
4322 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4323 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004324 }
4325 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004326
Richard Smith3003e1d2012-05-15 04:39:51 +00004327 if (HadError)
4328 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004329}
4330
Richard Smith7d5088a2012-02-18 02:02:13 +00004331namespace {
4332struct SpecialMemberDeletionInfo {
4333 Sema &S;
4334 CXXMethodDecl *MD;
4335 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004336 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004337
4338 // Properties of the special member, computed for convenience.
4339 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4340 SourceLocation Loc;
4341
4342 bool AllFieldsAreConst;
4343
4344 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004345 Sema::CXXSpecialMember CSM, bool Diagnose)
4346 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004347 IsConstructor(false), IsAssignment(false), IsMove(false),
4348 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4349 AllFieldsAreConst(true) {
4350 switch (CSM) {
4351 case Sema::CXXDefaultConstructor:
4352 case Sema::CXXCopyConstructor:
4353 IsConstructor = true;
4354 break;
4355 case Sema::CXXMoveConstructor:
4356 IsConstructor = true;
4357 IsMove = true;
4358 break;
4359 case Sema::CXXCopyAssignment:
4360 IsAssignment = true;
4361 break;
4362 case Sema::CXXMoveAssignment:
4363 IsAssignment = true;
4364 IsMove = true;
4365 break;
4366 case Sema::CXXDestructor:
4367 break;
4368 case Sema::CXXInvalid:
4369 llvm_unreachable("invalid special member kind");
4370 }
4371
4372 if (MD->getNumParams()) {
4373 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4374 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4375 }
4376 }
4377
4378 bool inUnion() const { return MD->getParent()->isUnion(); }
4379
4380 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004381 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4382 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004383 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004384 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4385 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4386 Quals = 0;
4387 return S.LookupSpecialMember(Class, CSM,
4388 ConstArg || (Quals & Qualifiers::Const),
4389 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004390 MD->getRefQualifier() == RQ_RValue,
4391 TQ & Qualifiers::Const,
4392 TQ & Qualifiers::Volatile);
4393 }
4394
Richard Smith6c4c36c2012-03-30 20:53:28 +00004395 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004396
Richard Smith6c4c36c2012-03-30 20:53:28 +00004397 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004398 bool shouldDeleteForField(FieldDecl *FD);
4399 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004400
Richard Smith517bb842012-07-18 03:51:16 +00004401 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4402 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004403 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4404 Sema::SpecialMemberOverloadResult *SMOR,
4405 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004406
4407 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004408};
4409}
4410
John McCall12d8d802012-04-09 20:53:23 +00004411/// Is the given special member inaccessible when used on the given
4412/// sub-object.
4413bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4414 CXXMethodDecl *target) {
4415 /// If we're operating on a base class, the object type is the
4416 /// type of this special member.
4417 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004418 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004419 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4420 objectTy = S.Context.getTypeDeclType(MD->getParent());
4421 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4422
4423 // If we're operating on a field, the object type is the type of the field.
4424 } else {
4425 objectTy = S.Context.getTypeDeclType(target->getParent());
4426 }
4427
4428 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4429}
4430
Richard Smith6c4c36c2012-03-30 20:53:28 +00004431/// Check whether we should delete a special member due to the implicit
4432/// definition containing a call to a special member of a subobject.
4433bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4434 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4435 bool IsDtorCallInCtor) {
4436 CXXMethodDecl *Decl = SMOR->getMethod();
4437 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4438
4439 int DiagKind = -1;
4440
4441 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4442 DiagKind = !Decl ? 0 : 1;
4443 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4444 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004445 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004446 DiagKind = 3;
4447 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4448 !Decl->isTrivial()) {
4449 // A member of a union must have a trivial corresponding special member.
4450 // As a weird special case, a destructor call from a union's constructor
4451 // must be accessible and non-deleted, but need not be trivial. Such a
4452 // destructor is never actually called, but is semantically checked as
4453 // if it were.
4454 DiagKind = 4;
4455 }
4456
4457 if (DiagKind == -1)
4458 return false;
4459
4460 if (Diagnose) {
4461 if (Field) {
4462 S.Diag(Field->getLocation(),
4463 diag::note_deleted_special_member_class_subobject)
4464 << CSM << MD->getParent() << /*IsField*/true
4465 << Field << DiagKind << IsDtorCallInCtor;
4466 } else {
4467 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4468 S.Diag(Base->getLocStart(),
4469 diag::note_deleted_special_member_class_subobject)
4470 << CSM << MD->getParent() << /*IsField*/false
4471 << Base->getType() << DiagKind << IsDtorCallInCtor;
4472 }
4473
4474 if (DiagKind == 1)
4475 S.NoteDeletedFunction(Decl);
4476 // FIXME: Explain inaccessibility if DiagKind == 3.
4477 }
4478
4479 return true;
4480}
4481
Richard Smith9a561d52012-02-26 09:11:52 +00004482/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004483/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004484bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004485 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004486 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004487
4488 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004489 // -- any direct or virtual base class, or non-static data member with no
4490 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004491 // either M has no default constructor or overload resolution as applied
4492 // to M's default constructor results in an ambiguity or in a function
4493 // that is deleted or inaccessible
4494 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4495 // -- a direct or virtual base class B that cannot be copied/moved because
4496 // overload resolution, as applied to B's corresponding special member,
4497 // results in an ambiguity or a function that is deleted or inaccessible
4498 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004499 // C++11 [class.dtor]p5:
4500 // -- any direct or virtual base class [...] has a type with a destructor
4501 // that is deleted or inaccessible
4502 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004503 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004504 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004505 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004506
Richard Smith6c4c36c2012-03-30 20:53:28 +00004507 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4508 // -- any direct or virtual base class or non-static data member has a
4509 // type with a destructor that is deleted or inaccessible
4510 if (IsConstructor) {
4511 Sema::SpecialMemberOverloadResult *SMOR =
4512 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4513 false, false, false, false, false);
4514 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4515 return true;
4516 }
4517
Richard Smith9a561d52012-02-26 09:11:52 +00004518 return false;
4519}
4520
4521/// Check whether we should delete a special member function due to the class
4522/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004523bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004524 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004525 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004526}
4527
4528/// Check whether we should delete a special member function due to the class
4529/// having a particular non-static data member.
4530bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4531 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4532 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4533
4534 if (CSM == Sema::CXXDefaultConstructor) {
4535 // For a default constructor, all references must be initialized in-class
4536 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004537 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4538 if (Diagnose)
4539 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4540 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004541 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004542 }
Richard Smith79363f52012-02-27 06:07:25 +00004543 // C++11 [class.ctor]p5: any non-variant non-static data member of
4544 // const-qualified type (or array thereof) with no
4545 // brace-or-equal-initializer does not have a user-provided default
4546 // constructor.
4547 if (!inUnion() && FieldType.isConstQualified() &&
4548 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004549 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4550 if (Diagnose)
4551 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004552 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004553 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004554 }
4555
4556 if (inUnion() && !FieldType.isConstQualified())
4557 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004558 } else if (CSM == Sema::CXXCopyConstructor) {
4559 // For a copy constructor, data members must not be of rvalue reference
4560 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004561 if (FieldType->isRValueReferenceType()) {
4562 if (Diagnose)
4563 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4564 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004565 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004566 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004567 } else if (IsAssignment) {
4568 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004569 if (FieldType->isReferenceType()) {
4570 if (Diagnose)
4571 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4572 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004573 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004574 }
4575 if (!FieldRecord && FieldType.isConstQualified()) {
4576 // C++11 [class.copy]p23:
4577 // -- a non-static data member of const non-class type (or array thereof)
4578 if (Diagnose)
4579 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004580 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004581 return true;
4582 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004583 }
4584
4585 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004586 // Some additional restrictions exist on the variant members.
4587 if (!inUnion() && FieldRecord->isUnion() &&
4588 FieldRecord->isAnonymousStructOrUnion()) {
4589 bool AllVariantFieldsAreConst = true;
4590
Richard Smithdf8dc862012-03-29 19:00:10 +00004591 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004592 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4593 UE = FieldRecord->field_end();
4594 UI != UE; ++UI) {
4595 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004596
4597 if (!UnionFieldType.isConstQualified())
4598 AllVariantFieldsAreConst = false;
4599
Richard Smith9a561d52012-02-26 09:11:52 +00004600 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4601 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004602 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4603 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004604 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004605 }
4606
4607 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004608 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004609 FieldRecord->field_begin() != FieldRecord->field_end()) {
4610 if (Diagnose)
4611 S.Diag(FieldRecord->getLocation(),
4612 diag::note_deleted_default_ctor_all_const)
4613 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004614 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004615 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004616
Richard Smithdf8dc862012-03-29 19:00:10 +00004617 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004618 // This is technically non-conformant, but sanity demands it.
4619 return false;
4620 }
4621
Richard Smith517bb842012-07-18 03:51:16 +00004622 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4623 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004624 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004625 }
4626
4627 return false;
4628}
4629
4630/// C++11 [class.ctor] p5:
4631/// A defaulted default constructor for a class X is defined as deleted if
4632/// X is a union and all of its variant members are of const-qualified type.
4633bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004634 // This is a silly definition, because it gives an empty union a deleted
4635 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004636 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4637 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4638 if (Diagnose)
4639 S.Diag(MD->getParent()->getLocation(),
4640 diag::note_deleted_default_ctor_all_const)
4641 << MD->getParent() << /*not anonymous union*/0;
4642 return true;
4643 }
4644 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004645}
4646
4647/// Determine whether a defaulted special member function should be defined as
4648/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4649/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004650bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4651 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004652 if (MD->isInvalidDecl())
4653 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004654 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004655 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004656 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004657 return false;
4658
Richard Smith7d5088a2012-02-18 02:02:13 +00004659 // C++11 [expr.lambda.prim]p19:
4660 // The closure type associated with a lambda-expression has a
4661 // deleted (8.4.3) default constructor and a deleted copy
4662 // assignment operator.
4663 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004664 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4665 if (Diagnose)
4666 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004667 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004668 }
4669
Richard Smith5bdaac52012-04-02 20:59:25 +00004670 // For an anonymous struct or union, the copy and assignment special members
4671 // will never be used, so skip the check. For an anonymous union declared at
4672 // namespace scope, the constructor and destructor are used.
4673 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4674 RD->isAnonymousStructOrUnion())
4675 return false;
4676
Richard Smith6c4c36c2012-03-30 20:53:28 +00004677 // C++11 [class.copy]p7, p18:
4678 // If the class definition declares a move constructor or move assignment
4679 // operator, an implicitly declared copy constructor or copy assignment
4680 // operator is defined as deleted.
4681 if (MD->isImplicit() &&
4682 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4683 CXXMethodDecl *UserDeclaredMove = 0;
4684
4685 // In Microsoft mode, a user-declared move only causes the deletion of the
4686 // corresponding copy operation, not both copy operations.
4687 if (RD->hasUserDeclaredMoveConstructor() &&
4688 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4689 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004690
4691 // Find any user-declared move constructor.
4692 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4693 E = RD->ctor_end(); I != E; ++I) {
4694 if (I->isMoveConstructor()) {
4695 UserDeclaredMove = *I;
4696 break;
4697 }
4698 }
Richard Smith1c931be2012-04-02 18:40:40 +00004699 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004700 } else if (RD->hasUserDeclaredMoveAssignment() &&
4701 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4702 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004703
4704 // Find any user-declared move assignment operator.
4705 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4706 E = RD->method_end(); I != E; ++I) {
4707 if (I->isMoveAssignmentOperator()) {
4708 UserDeclaredMove = *I;
4709 break;
4710 }
4711 }
Richard Smith1c931be2012-04-02 18:40:40 +00004712 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004713 }
4714
4715 if (UserDeclaredMove) {
4716 Diag(UserDeclaredMove->getLocation(),
4717 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004718 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004719 << UserDeclaredMove->isMoveAssignmentOperator();
4720 return true;
4721 }
4722 }
Sean Hunte16da072011-10-10 06:18:57 +00004723
Richard Smith5bdaac52012-04-02 20:59:25 +00004724 // Do access control from the special member function
4725 ContextRAII MethodContext(*this, MD);
4726
Richard Smith9a561d52012-02-26 09:11:52 +00004727 // C++11 [class.dtor]p5:
4728 // -- for a virtual destructor, lookup of the non-array deallocation function
4729 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004730 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004731 FunctionDecl *OperatorDelete = 0;
4732 DeclarationName Name =
4733 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4734 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004735 OperatorDelete, false)) {
4736 if (Diagnose)
4737 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004738 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004739 }
Richard Smith9a561d52012-02-26 09:11:52 +00004740 }
4741
Richard Smith6c4c36c2012-03-30 20:53:28 +00004742 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004743
Sean Huntcdee3fe2011-05-11 22:34:38 +00004744 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004745 BE = RD->bases_end(); BI != BE; ++BI)
4746 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004747 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004748 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004749
4750 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004751 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004752 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004753 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004754
4755 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004756 FE = RD->field_end(); FI != FE; ++FI)
4757 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004758 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004759 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004760
Richard Smith7d5088a2012-02-18 02:02:13 +00004761 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004762 return true;
4763
4764 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004765}
4766
Richard Smithac713512012-12-08 02:53:02 +00004767/// Perform lookup for a special member of the specified kind, and determine
4768/// whether it is trivial. If the triviality can be determined without the
4769/// lookup, skip it. This is intended for use when determining whether a
4770/// special member of a containing object is trivial, and thus does not ever
4771/// perform overload resolution for default constructors.
4772///
4773/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4774/// member that was most likely to be intended to be trivial, if any.
4775static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4776 Sema::CXXSpecialMember CSM, unsigned Quals,
4777 CXXMethodDecl **Selected) {
4778 if (Selected)
4779 *Selected = 0;
4780
4781 switch (CSM) {
4782 case Sema::CXXInvalid:
4783 llvm_unreachable("not a special member");
4784
4785 case Sema::CXXDefaultConstructor:
4786 // C++11 [class.ctor]p5:
4787 // A default constructor is trivial if:
4788 // - all the [direct subobjects] have trivial default constructors
4789 //
4790 // Note, no overload resolution is performed in this case.
4791 if (RD->hasTrivialDefaultConstructor())
4792 return true;
4793
4794 if (Selected) {
4795 // If there's a default constructor which could have been trivial, dig it
4796 // out. Otherwise, if there's any user-provided default constructor, point
4797 // to that as an example of why there's not a trivial one.
4798 CXXConstructorDecl *DefCtor = 0;
4799 if (RD->needsImplicitDefaultConstructor())
4800 S.DeclareImplicitDefaultConstructor(RD);
4801 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4802 CE = RD->ctor_end(); CI != CE; ++CI) {
4803 if (!CI->isDefaultConstructor())
4804 continue;
4805 DefCtor = *CI;
4806 if (!DefCtor->isUserProvided())
4807 break;
4808 }
4809
4810 *Selected = DefCtor;
4811 }
4812
4813 return false;
4814
4815 case Sema::CXXDestructor:
4816 // C++11 [class.dtor]p5:
4817 // A destructor is trivial if:
4818 // - all the direct [subobjects] have trivial destructors
4819 if (RD->hasTrivialDestructor())
4820 return true;
4821
4822 if (Selected) {
4823 if (RD->needsImplicitDestructor())
4824 S.DeclareImplicitDestructor(RD);
4825 *Selected = RD->getDestructor();
4826 }
4827
4828 return false;
4829
4830 case Sema::CXXCopyConstructor:
4831 // C++11 [class.copy]p12:
4832 // A copy constructor is trivial if:
4833 // - the constructor selected to copy each direct [subobject] is trivial
4834 if (RD->hasTrivialCopyConstructor()) {
4835 if (Quals == Qualifiers::Const)
4836 // We must either select the trivial copy constructor or reach an
4837 // ambiguity; no need to actually perform overload resolution.
4838 return true;
4839 } else if (!Selected) {
4840 return false;
4841 }
4842 // In C++98, we are not supposed to perform overload resolution here, but we
4843 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4844 // cases like B as having a non-trivial copy constructor:
4845 // struct A { template<typename T> A(T&); };
4846 // struct B { mutable A a; };
4847 goto NeedOverloadResolution;
4848
4849 case Sema::CXXCopyAssignment:
4850 // C++11 [class.copy]p25:
4851 // A copy assignment operator is trivial if:
4852 // - the assignment operator selected to copy each direct [subobject] is
4853 // trivial
4854 if (RD->hasTrivialCopyAssignment()) {
4855 if (Quals == Qualifiers::Const)
4856 return true;
4857 } else if (!Selected) {
4858 return false;
4859 }
4860 // In C++98, we are not supposed to perform overload resolution here, but we
4861 // treat that as a language defect.
4862 goto NeedOverloadResolution;
4863
4864 case Sema::CXXMoveConstructor:
4865 case Sema::CXXMoveAssignment:
4866 NeedOverloadResolution:
4867 Sema::SpecialMemberOverloadResult *SMOR =
4868 S.LookupSpecialMember(RD, CSM,
4869 Quals & Qualifiers::Const,
4870 Quals & Qualifiers::Volatile,
4871 /*RValueThis*/false, /*ConstThis*/false,
4872 /*VolatileThis*/false);
4873
4874 // The standard doesn't describe how to behave if the lookup is ambiguous.
4875 // We treat it as not making the member non-trivial, just like the standard
4876 // mandates for the default constructor. This should rarely matter, because
4877 // the member will also be deleted.
4878 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4879 return true;
4880
4881 if (!SMOR->getMethod()) {
4882 assert(SMOR->getKind() ==
4883 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4884 return false;
4885 }
4886
4887 // We deliberately don't check if we found a deleted special member. We're
4888 // not supposed to!
4889 if (Selected)
4890 *Selected = SMOR->getMethod();
4891 return SMOR->getMethod()->isTrivial();
4892 }
4893
4894 llvm_unreachable("unknown special method kind");
4895}
4896
4897CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4898 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4899 CI != CE; ++CI)
4900 if (!CI->isImplicit())
4901 return *CI;
4902
4903 // Look for constructor templates.
4904 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4905 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4906 if (CXXConstructorDecl *CD =
4907 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4908 return CD;
4909 }
4910
4911 return 0;
4912}
4913
4914/// The kind of subobject we are checking for triviality. The values of this
4915/// enumeration are used in diagnostics.
4916enum TrivialSubobjectKind {
4917 /// The subobject is a base class.
4918 TSK_BaseClass,
4919 /// The subobject is a non-static data member.
4920 TSK_Field,
4921 /// The object is actually the complete object.
4922 TSK_CompleteObject
4923};
4924
4925/// Check whether the special member selected for a given type would be trivial.
4926static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4927 QualType SubType,
4928 Sema::CXXSpecialMember CSM,
4929 TrivialSubobjectKind Kind,
4930 bool Diagnose) {
4931 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4932 if (!SubRD)
4933 return true;
4934
4935 CXXMethodDecl *Selected;
4936 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4937 Diagnose ? &Selected : 0))
4938 return true;
4939
4940 if (Diagnose) {
4941 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4942 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4943 << Kind << SubType.getUnqualifiedType();
4944 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4945 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4946 } else if (!Selected)
4947 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
4948 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
4949 else if (Selected->isUserProvided()) {
4950 if (Kind == TSK_CompleteObject)
4951 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
4952 << Kind << SubType.getUnqualifiedType() << CSM;
4953 else {
4954 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
4955 << Kind << SubType.getUnqualifiedType() << CSM;
4956 S.Diag(Selected->getLocation(), diag::note_declared_at);
4957 }
4958 } else {
4959 if (Kind != TSK_CompleteObject)
4960 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
4961 << Kind << SubType.getUnqualifiedType() << CSM;
4962
4963 // Explain why the defaulted or deleted special member isn't trivial.
4964 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
4965 }
4966 }
4967
4968 return false;
4969}
4970
4971/// Check whether the members of a class type allow a special member to be
4972/// trivial.
4973static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
4974 Sema::CXXSpecialMember CSM,
4975 bool ConstArg, bool Diagnose) {
4976 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4977 FE = RD->field_end(); FI != FE; ++FI) {
4978 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
4979 continue;
4980
4981 QualType FieldType = S.Context.getBaseElementType(FI->getType());
4982
4983 // Pretend anonymous struct or union members are members of this class.
4984 if (FI->isAnonymousStructOrUnion()) {
4985 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
4986 CSM, ConstArg, Diagnose))
4987 return false;
4988 continue;
4989 }
4990
4991 // C++11 [class.ctor]p5:
4992 // A default constructor is trivial if [...]
4993 // -- no non-static data member of its class has a
4994 // brace-or-equal-initializer
4995 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
4996 if (Diagnose)
4997 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
4998 return false;
4999 }
5000
5001 // Objective C ARC 4.3.5:
5002 // [...] nontrivally ownership-qualified types are [...] not trivially
5003 // default constructible, copy constructible, move constructible, copy
5004 // assignable, move assignable, or destructible [...]
5005 if (S.getLangOpts().ObjCAutoRefCount &&
5006 FieldType.hasNonTrivialObjCLifetime()) {
5007 if (Diagnose)
5008 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5009 << RD << FieldType.getObjCLifetime();
5010 return false;
5011 }
5012
5013 if (ConstArg && !FI->isMutable())
5014 FieldType.addConst();
5015 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5016 TSK_Field, Diagnose))
5017 return false;
5018 }
5019
5020 return true;
5021}
5022
5023/// Diagnose why the specified class does not have a trivial special member of
5024/// the given kind.
5025void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5026 QualType Ty = Context.getRecordType(RD);
5027 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5028 Ty.addConst();
5029
5030 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5031 TSK_CompleteObject, /*Diagnose*/true);
5032}
5033
5034/// Determine whether a defaulted or deleted special member function is trivial,
5035/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5036/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5037bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5038 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005039 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5040
5041 CXXRecordDecl *RD = MD->getParent();
5042
5043 bool ConstArg = false;
5044 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5045
5046 // C++11 [class.copy]p12, p25:
5047 // A [special member] is trivial if its declared parameter type is the same
5048 // as if it had been implicitly declared [...]
5049 switch (CSM) {
5050 case CXXDefaultConstructor:
5051 case CXXDestructor:
5052 // Trivial default constructors and destructors cannot have parameters.
5053 break;
5054
5055 case CXXCopyConstructor:
5056 case CXXCopyAssignment: {
5057 // Trivial copy operations always have const, non-volatile parameter types.
5058 ConstArg = true;
5059 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5060 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5061 if (Diagnose)
5062 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5063 << Param0->getSourceRange() << Param0->getType()
5064 << Context.getLValueReferenceType(
5065 Context.getRecordType(RD).withConst());
5066 return false;
5067 }
5068 break;
5069 }
5070
5071 case CXXMoveConstructor:
5072 case CXXMoveAssignment: {
5073 // Trivial move operations always have non-cv-qualified parameters.
5074 const RValueReferenceType *RT =
5075 Param0->getType()->getAs<RValueReferenceType>();
5076 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5077 if (Diagnose)
5078 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5079 << Param0->getSourceRange() << Param0->getType()
5080 << Context.getRValueReferenceType(Context.getRecordType(RD));
5081 return false;
5082 }
5083 break;
5084 }
5085
5086 case CXXInvalid:
5087 llvm_unreachable("not a special member");
5088 }
5089
5090 // FIXME: We require that the parameter-declaration-clause is equivalent to
5091 // that of an implicit declaration, not just that the declared parameter type
5092 // matches, in order to prevent absuridities like a function simultaneously
5093 // being a trivial copy constructor and a non-trivial default constructor.
5094 // This issue has not yet been assigned a core issue number.
5095 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5096 if (Diagnose)
5097 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5098 diag::note_nontrivial_default_arg)
5099 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5100 return false;
5101 }
5102 if (MD->isVariadic()) {
5103 if (Diagnose)
5104 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5105 return false;
5106 }
5107
5108 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5109 // A copy/move [constructor or assignment operator] is trivial if
5110 // -- the [member] selected to copy/move each direct base class subobject
5111 // is trivial
5112 //
5113 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5114 // A [default constructor or destructor] is trivial if
5115 // -- all the direct base classes have trivial [default constructors or
5116 // destructors]
5117 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5118 BE = RD->bases_end(); BI != BE; ++BI)
5119 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5120 ConstArg ? BI->getType().withConst()
5121 : BI->getType(),
5122 CSM, TSK_BaseClass, Diagnose))
5123 return false;
5124
5125 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5126 // A copy/move [constructor or assignment operator] for a class X is
5127 // trivial if
5128 // -- for each non-static data member of X that is of class type (or array
5129 // thereof), the constructor selected to copy/move that member is
5130 // trivial
5131 //
5132 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5133 // A [default constructor or destructor] is trivial if
5134 // -- for all of the non-static data members of its class that are of class
5135 // type (or array thereof), each such class has a trivial [default
5136 // constructor or destructor]
5137 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5138 return false;
5139
5140 // C++11 [class.dtor]p5:
5141 // A destructor is trivial if [...]
5142 // -- the destructor is not virtual
5143 if (CSM == CXXDestructor && MD->isVirtual()) {
5144 if (Diagnose)
5145 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5146 return false;
5147 }
5148
5149 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5150 // A [special member] for class X is trivial if [...]
5151 // -- class X has no virtual functions and no virtual base classes
5152 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5153 if (!Diagnose)
5154 return false;
5155
5156 if (RD->getNumVBases()) {
5157 // Check for virtual bases. We already know that the corresponding
5158 // member in all bases is trivial, so vbases must all be direct.
5159 CXXBaseSpecifier &BS = *RD->vbases_begin();
5160 assert(BS.isVirtual());
5161 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5162 return false;
5163 }
5164
5165 // Must have a virtual method.
5166 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5167 ME = RD->method_end(); MI != ME; ++MI) {
5168 if (MI->isVirtual()) {
5169 SourceLocation MLoc = MI->getLocStart();
5170 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5171 return false;
5172 }
5173 }
5174
5175 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5176 }
5177
5178 // Looks like it's trivial!
5179 return true;
5180}
5181
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005182/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005183namespace {
5184 struct FindHiddenVirtualMethodData {
5185 Sema *S;
5186 CXXMethodDecl *Method;
5187 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005188 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005189 };
5190}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005191
David Blaikie5f750682012-10-19 00:53:08 +00005192/// \brief Check whether any most overriden method from MD in Methods
5193static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5194 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5195 if (MD->size_overridden_methods() == 0)
5196 return Methods.count(MD->getCanonicalDecl());
5197 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5198 E = MD->end_overridden_methods();
5199 I != E; ++I)
5200 if (CheckMostOverridenMethods(*I, Methods))
5201 return true;
5202 return false;
5203}
5204
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005205/// \brief Member lookup function that determines whether a given C++
5206/// method overloads virtual methods in a base class without overriding any,
5207/// to be used with CXXRecordDecl::lookupInBases().
5208static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5209 CXXBasePath &Path,
5210 void *UserData) {
5211 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5212
5213 FindHiddenVirtualMethodData &Data
5214 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5215
5216 DeclarationName Name = Data.Method->getDeclName();
5217 assert(Name.getNameKind() == DeclarationName::Identifier);
5218
5219 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005220 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005221 for (Path.Decls = BaseRecord->lookup(Name);
5222 Path.Decls.first != Path.Decls.second;
5223 ++Path.Decls.first) {
5224 NamedDecl *D = *Path.Decls.first;
5225 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005226 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005227 foundSameNameMethod = true;
5228 // Interested only in hidden virtual methods.
5229 if (!MD->isVirtual())
5230 continue;
5231 // If the method we are checking overrides a method from its base
5232 // don't warn about the other overloaded methods.
5233 if (!Data.S->IsOverload(Data.Method, MD, false))
5234 return true;
5235 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005236 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005237 overloadedMethods.push_back(MD);
5238 }
5239 }
5240
5241 if (foundSameNameMethod)
5242 Data.OverloadedMethods.append(overloadedMethods.begin(),
5243 overloadedMethods.end());
5244 return foundSameNameMethod;
5245}
5246
David Blaikie5f750682012-10-19 00:53:08 +00005247/// \brief Add the most overriden methods from MD to Methods
5248static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5249 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5250 if (MD->size_overridden_methods() == 0)
5251 Methods.insert(MD->getCanonicalDecl());
5252 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5253 E = MD->end_overridden_methods();
5254 I != E; ++I)
5255 AddMostOverridenMethods(*I, Methods);
5256}
5257
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005258/// \brief See if a method overloads virtual methods in a base class without
5259/// overriding any.
5260void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5261 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005262 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005263 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005264 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005265 return;
5266
5267 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5268 /*bool RecordPaths=*/false,
5269 /*bool DetectVirtual=*/false);
5270 FindHiddenVirtualMethodData Data;
5271 Data.Method = MD;
5272 Data.S = this;
5273
5274 // Keep the base methods that were overriden or introduced in the subclass
5275 // by 'using' in a set. A base method not in this set is hidden.
5276 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5277 res.first != res.second; ++res.first) {
David Blaikie5f750682012-10-19 00:53:08 +00005278 NamedDecl *ND = *res.first;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005279 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
David Blaikie5f750682012-10-19 00:53:08 +00005280 ND = shad->getTargetDecl();
5281 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5282 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005283 }
5284
5285 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5286 !Data.OverloadedMethods.empty()) {
5287 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5288 << MD << (Data.OverloadedMethods.size() > 1);
5289
5290 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5291 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5292 Diag(overloadedMD->getLocation(),
5293 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5294 }
5295 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005296}
5297
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005298void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005299 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005300 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005301 SourceLocation RBrac,
5302 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005303 if (!TagDecl)
5304 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005305
Douglas Gregor42af25f2009-05-11 19:58:34 +00005306 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005307
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005308 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5309 if (l->getKind() != AttributeList::AT_Visibility)
5310 continue;
5311 l->setInvalid();
5312 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5313 l->getName();
5314 }
5315
David Blaikie77b6de02011-09-22 02:58:26 +00005316 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005317 // strict aliasing violation!
5318 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005319 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005320
Douglas Gregor23c94db2010-07-02 17:43:08 +00005321 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005322 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005323}
5324
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005325/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5326/// special functions, such as the default constructor, copy
5327/// constructor, or destructor, to the given C++ class (C++
5328/// [special]p1). This routine can only be executed just before the
5329/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005330void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005331 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005332 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005333
Richard Smithbc2a35d2012-12-08 08:32:28 +00005334 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005335 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005336
Richard Smithbc2a35d2012-12-08 08:32:28 +00005337 // If the properties or semantics of the copy constructor couldn't be
5338 // determined while the class was being declared, force a declaration
5339 // of it now.
5340 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5341 DeclareImplicitCopyConstructor(ClassDecl);
5342 }
5343
5344 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005345 ++ASTContext::NumImplicitMoveConstructors;
5346
Richard Smithbc2a35d2012-12-08 08:32:28 +00005347 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5348 DeclareImplicitMoveConstructor(ClassDecl);
5349 }
5350
Douglas Gregora376d102010-07-02 21:50:04 +00005351 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5352 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005353
5354 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005355 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005356 // it shows up in the right place in the vtable and that we diagnose
5357 // problems with the implicit exception specification.
5358 if (ClassDecl->isDynamicClass() ||
5359 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005360 DeclareImplicitCopyAssignment(ClassDecl);
5361 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005362
Richard Smith1c931be2012-04-02 18:40:40 +00005363 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005364 ++ASTContext::NumImplicitMoveAssignmentOperators;
5365
5366 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005367 if (ClassDecl->isDynamicClass() ||
5368 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005369 DeclareImplicitMoveAssignment(ClassDecl);
5370 }
5371
Douglas Gregor4923aa22010-07-02 20:37:36 +00005372 if (!ClassDecl->hasUserDeclaredDestructor()) {
5373 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005374
5375 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005376 // have to declare the destructor immediately. This ensures that, e.g., it
5377 // shows up in the right place in the vtable and that we diagnose problems
5378 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005379 if (ClassDecl->isDynamicClass() ||
5380 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005381 DeclareImplicitDestructor(ClassDecl);
5382 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005383}
5384
Francois Pichet8387e2a2011-04-22 22:18:13 +00005385void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5386 if (!D)
5387 return;
5388
5389 int NumParamList = D->getNumTemplateParameterLists();
5390 for (int i = 0; i < NumParamList; i++) {
5391 TemplateParameterList* Params = D->getTemplateParameterList(i);
5392 for (TemplateParameterList::iterator Param = Params->begin(),
5393 ParamEnd = Params->end();
5394 Param != ParamEnd; ++Param) {
5395 NamedDecl *Named = cast<NamedDecl>(*Param);
5396 if (Named->getDeclName()) {
5397 S->AddDecl(Named);
5398 IdResolver.AddDecl(Named);
5399 }
5400 }
5401 }
5402}
5403
John McCalld226f652010-08-21 09:40:31 +00005404void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005405 if (!D)
5406 return;
5407
5408 TemplateParameterList *Params = 0;
5409 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5410 Params = Template->getTemplateParameters();
5411 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5412 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5413 Params = PartialSpec->getTemplateParameters();
5414 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005415 return;
5416
Douglas Gregor6569d682009-05-27 23:11:45 +00005417 for (TemplateParameterList::iterator Param = Params->begin(),
5418 ParamEnd = Params->end();
5419 Param != ParamEnd; ++Param) {
5420 NamedDecl *Named = cast<NamedDecl>(*Param);
5421 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005422 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005423 IdResolver.AddDecl(Named);
5424 }
5425 }
5426}
5427
John McCalld226f652010-08-21 09:40:31 +00005428void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005429 if (!RecordD) return;
5430 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005431 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005432 PushDeclContext(S, Record);
5433}
5434
John McCalld226f652010-08-21 09:40:31 +00005435void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005436 if (!RecordD) return;
5437 PopDeclContext();
5438}
5439
Douglas Gregor72b505b2008-12-16 21:30:33 +00005440/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5441/// parsing a top-level (non-nested) C++ class, and we are now
5442/// parsing those parts of the given Method declaration that could
5443/// not be parsed earlier (C++ [class.mem]p2), such as default
5444/// arguments. This action should enter the scope of the given
5445/// Method declaration as if we had just parsed the qualified method
5446/// name. However, it should not bring the parameters into scope;
5447/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005448void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005449}
5450
5451/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5452/// C++ method declaration. We're (re-)introducing the given
5453/// function parameter into scope for use in parsing later parts of
5454/// the method declaration. For example, we could see an
5455/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005456void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005457 if (!ParamD)
5458 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005459
John McCalld226f652010-08-21 09:40:31 +00005460 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005461
5462 // If this parameter has an unparsed default argument, clear it out
5463 // to make way for the parsed default argument.
5464 if (Param->hasUnparsedDefaultArg())
5465 Param->setDefaultArg(0);
5466
John McCalld226f652010-08-21 09:40:31 +00005467 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005468 if (Param->getDeclName())
5469 IdResolver.AddDecl(Param);
5470}
5471
5472/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5473/// processing the delayed method declaration for Method. The method
5474/// declaration is now considered finished. There may be a separate
5475/// ActOnStartOfFunctionDef action later (not necessarily
5476/// immediately!) for this method, if it was also defined inside the
5477/// class body.
John McCalld226f652010-08-21 09:40:31 +00005478void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005479 if (!MethodD)
5480 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005481
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005482 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005483
John McCalld226f652010-08-21 09:40:31 +00005484 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005485
5486 // Now that we have our default arguments, check the constructor
5487 // again. It could produce additional diagnostics or affect whether
5488 // the class has implicitly-declared destructors, among other
5489 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005490 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5491 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005492
5493 // Check the default arguments, which we may have added.
5494 if (!Method->isInvalidDecl())
5495 CheckCXXDefaultArguments(Method);
5496}
5497
Douglas Gregor42a552f2008-11-05 20:51:48 +00005498/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005499/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005500/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005501/// emit diagnostics and set the invalid bit to true. In any case, the type
5502/// will be updated to reflect a well-formed type for the constructor and
5503/// returned.
5504QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005505 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005506 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005507
5508 // C++ [class.ctor]p3:
5509 // A constructor shall not be virtual (10.3) or static (9.4). A
5510 // constructor can be invoked for a const, volatile or const
5511 // volatile object. A constructor shall not be declared const,
5512 // volatile, or const volatile (9.3.2).
5513 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005514 if (!D.isInvalidType())
5515 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5516 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5517 << SourceRange(D.getIdentifierLoc());
5518 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005519 }
John McCalld931b082010-08-26 03:08:43 +00005520 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005521 if (!D.isInvalidType())
5522 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5523 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5524 << SourceRange(D.getIdentifierLoc());
5525 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005526 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005527 }
Mike Stump1eb44332009-09-09 15:08:12 +00005528
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005529 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005530 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005531 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005532 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5533 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005534 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005535 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5536 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005537 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005538 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5539 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005540 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005541 }
Mike Stump1eb44332009-09-09 15:08:12 +00005542
Douglas Gregorc938c162011-01-26 05:01:58 +00005543 // C++0x [class.ctor]p4:
5544 // A constructor shall not be declared with a ref-qualifier.
5545 if (FTI.hasRefQualifier()) {
5546 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5547 << FTI.RefQualifierIsLValueRef
5548 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5549 D.setInvalidType();
5550 }
5551
Douglas Gregor42a552f2008-11-05 20:51:48 +00005552 // Rebuild the function type "R" without any type qualifiers (in
5553 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005554 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005555 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005556 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5557 return R;
5558
5559 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5560 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005561 EPI.RefQualifier = RQ_None;
5562
Chris Lattner65401802009-04-25 08:28:21 +00005563 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005564 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005565}
5566
Douglas Gregor72b505b2008-12-16 21:30:33 +00005567/// CheckConstructor - Checks a fully-formed constructor for
5568/// well-formedness, issuing any diagnostics required. Returns true if
5569/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005570void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005571 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005572 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5573 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005574 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005575
5576 // C++ [class.copy]p3:
5577 // A declaration of a constructor for a class X is ill-formed if
5578 // its first parameter is of type (optionally cv-qualified) X and
5579 // either there are no other parameters or else all other
5580 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005581 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005582 ((Constructor->getNumParams() == 1) ||
5583 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005584 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5585 Constructor->getTemplateSpecializationKind()
5586 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005587 QualType ParamType = Constructor->getParamDecl(0)->getType();
5588 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5589 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005590 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005591 const char *ConstRef
5592 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5593 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005594 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005595 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005596
5597 // FIXME: Rather that making the constructor invalid, we should endeavor
5598 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005599 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005600 }
5601 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005602}
5603
John McCall15442822010-08-04 01:04:25 +00005604/// CheckDestructor - Checks a fully-formed destructor definition for
5605/// well-formedness, issuing any diagnostics required. Returns true
5606/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005607bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005608 CXXRecordDecl *RD = Destructor->getParent();
5609
5610 if (Destructor->isVirtual()) {
5611 SourceLocation Loc;
5612
5613 if (!Destructor->isImplicit())
5614 Loc = Destructor->getLocation();
5615 else
5616 Loc = RD->getLocation();
5617
5618 // If we have a virtual destructor, look up the deallocation function
5619 FunctionDecl *OperatorDelete = 0;
5620 DeclarationName Name =
5621 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005622 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005623 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005624
Eli Friedman5f2987c2012-02-02 03:46:19 +00005625 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005626
5627 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005628 }
Anders Carlsson37909802009-11-30 21:24:50 +00005629
5630 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005631}
5632
Mike Stump1eb44332009-09-09 15:08:12 +00005633static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005634FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5635 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5636 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005637 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005638}
5639
Douglas Gregor42a552f2008-11-05 20:51:48 +00005640/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5641/// the well-formednes of the destructor declarator @p D with type @p
5642/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005643/// emit diagnostics and set the declarator to invalid. Even if this happens,
5644/// will be updated to reflect a well-formed type for the destructor and
5645/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005646QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005647 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005648 // C++ [class.dtor]p1:
5649 // [...] A typedef-name that names a class is a class-name
5650 // (7.1.3); however, a typedef-name that names a class shall not
5651 // be used as the identifier in the declarator for a destructor
5652 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005653 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005654 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005655 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005656 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005657 else if (const TemplateSpecializationType *TST =
5658 DeclaratorType->getAs<TemplateSpecializationType>())
5659 if (TST->isTypeAlias())
5660 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5661 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005662
5663 // C++ [class.dtor]p2:
5664 // A destructor is used to destroy objects of its class type. A
5665 // destructor takes no parameters, and no return type can be
5666 // specified for it (not even void). The address of a destructor
5667 // shall not be taken. A destructor shall not be static. A
5668 // destructor can be invoked for a const, volatile or const
5669 // volatile object. A destructor shall not be declared const,
5670 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005671 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005672 if (!D.isInvalidType())
5673 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5674 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005675 << SourceRange(D.getIdentifierLoc())
5676 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5677
John McCalld931b082010-08-26 03:08:43 +00005678 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005679 }
Chris Lattner65401802009-04-25 08:28:21 +00005680 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005681 // Destructors don't have return types, but the parser will
5682 // happily parse something like:
5683 //
5684 // class X {
5685 // float ~X();
5686 // };
5687 //
5688 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005689 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5690 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5691 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005692 }
Mike Stump1eb44332009-09-09 15:08:12 +00005693
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005694 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005695 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005696 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005697 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5698 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005699 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005700 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5701 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005702 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005703 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5704 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005705 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005706 }
5707
Douglas Gregorc938c162011-01-26 05:01:58 +00005708 // C++0x [class.dtor]p2:
5709 // A destructor shall not be declared with a ref-qualifier.
5710 if (FTI.hasRefQualifier()) {
5711 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5712 << FTI.RefQualifierIsLValueRef
5713 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5714 D.setInvalidType();
5715 }
5716
Douglas Gregor42a552f2008-11-05 20:51:48 +00005717 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005718 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005719 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5720
5721 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005722 FTI.freeArgs();
5723 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005724 }
5725
Mike Stump1eb44332009-09-09 15:08:12 +00005726 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005727 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005728 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005729 D.setInvalidType();
5730 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005731
5732 // Rebuild the function type "R" without any type qualifiers or
5733 // parameters (in case any of the errors above fired) and with
5734 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005735 // types.
John McCalle23cf432010-12-14 08:05:40 +00005736 if (!D.isInvalidType())
5737 return R;
5738
Douglas Gregord92ec472010-07-01 05:10:53 +00005739 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005740 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5741 EPI.Variadic = false;
5742 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005743 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005744 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005745}
5746
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005747/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5748/// well-formednes of the conversion function declarator @p D with
5749/// type @p R. If there are any errors in the declarator, this routine
5750/// will emit diagnostics and return true. Otherwise, it will return
5751/// false. Either way, the type @p R will be updated to reflect a
5752/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005753void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005754 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005755 // C++ [class.conv.fct]p1:
5756 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005757 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005758 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005759 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005760 if (!D.isInvalidType())
5761 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5762 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5763 << SourceRange(D.getIdentifierLoc());
5764 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005765 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005766 }
John McCalla3f81372010-04-13 00:04:31 +00005767
5768 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5769
Chris Lattner6e475012009-04-25 08:35:12 +00005770 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005771 // Conversion functions don't have return types, but the parser will
5772 // happily parse something like:
5773 //
5774 // class X {
5775 // float operator bool();
5776 // };
5777 //
5778 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005779 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5780 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5781 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005782 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005783 }
5784
John McCalla3f81372010-04-13 00:04:31 +00005785 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5786
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005787 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005788 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005789 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5790
5791 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005792 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005793 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005794 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005795 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005796 D.setInvalidType();
5797 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005798
John McCalla3f81372010-04-13 00:04:31 +00005799 // Diagnose "&operator bool()" and other such nonsense. This
5800 // is actually a gcc extension which we don't support.
5801 if (Proto->getResultType() != ConvType) {
5802 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5803 << Proto->getResultType();
5804 D.setInvalidType();
5805 ConvType = Proto->getResultType();
5806 }
5807
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005808 // C++ [class.conv.fct]p4:
5809 // The conversion-type-id shall not represent a function type nor
5810 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005811 if (ConvType->isArrayType()) {
5812 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5813 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005814 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005815 } else if (ConvType->isFunctionType()) {
5816 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5817 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005818 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005819 }
5820
5821 // Rebuild the function type "R" without any parameters (in case any
5822 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005823 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005824 if (D.isInvalidType())
5825 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005826
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005827 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005828 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005829 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005830 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005831 diag::warn_cxx98_compat_explicit_conversion_functions :
5832 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005833 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005834}
5835
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005836/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5837/// the declaration of the given C++ conversion function. This routine
5838/// is responsible for recording the conversion function in the C++
5839/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005840Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005841 assert(Conversion && "Expected to receive a conversion function declaration");
5842
Douglas Gregor9d350972008-12-12 08:25:50 +00005843 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005844
5845 // Make sure we aren't redeclaring the conversion function.
5846 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005847
5848 // C++ [class.conv.fct]p1:
5849 // [...] A conversion function is never used to convert a
5850 // (possibly cv-qualified) object to the (possibly cv-qualified)
5851 // same object type (or a reference to it), to a (possibly
5852 // cv-qualified) base class of that type (or a reference to it),
5853 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005854 // FIXME: Suppress this warning if the conversion function ends up being a
5855 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005856 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005857 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005858 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005859 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005860 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5861 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005862 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005863 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005864 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5865 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005866 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005867 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005868 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005869 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005870 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005871 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005872 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005873 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005874 }
5875
Douglas Gregore80622f2010-09-29 04:25:11 +00005876 if (FunctionTemplateDecl *ConversionTemplate
5877 = Conversion->getDescribedFunctionTemplate())
5878 return ConversionTemplate;
5879
John McCalld226f652010-08-21 09:40:31 +00005880 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005881}
5882
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005883//===----------------------------------------------------------------------===//
5884// Namespace Handling
5885//===----------------------------------------------------------------------===//
5886
Richard Smithd1a55a62012-10-04 22:13:39 +00005887/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5888/// reopened.
5889static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5890 SourceLocation Loc,
5891 IdentifierInfo *II, bool *IsInline,
5892 NamespaceDecl *PrevNS) {
5893 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005894
Richard Smithc969e6a2012-10-05 01:46:25 +00005895 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5896 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5897 // inline namespaces, with the intention of bringing names into namespace std.
5898 //
5899 // We support this just well enough to get that case working; this is not
5900 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005901 if (*IsInline && II && II->getName().startswith("__atomic") &&
5902 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005903 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005904 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5905 NS = NS->getPreviousDecl())
5906 NS->setInline(*IsInline);
5907 // Patch up the lookup table for the containing namespace. This isn't really
5908 // correct, but it's good enough for this particular case.
5909 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5910 E = PrevNS->decls_end(); I != E; ++I)
5911 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5912 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5913 return;
5914 }
5915
5916 if (PrevNS->isInline())
5917 // The user probably just forgot the 'inline', so suggest that it
5918 // be added back.
5919 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5920 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5921 else
5922 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5923 << IsInline;
5924
5925 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5926 *IsInline = PrevNS->isInline();
5927}
John McCallea318642010-08-26 09:15:37 +00005928
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005929/// ActOnStartNamespaceDef - This is called at the start of a namespace
5930/// definition.
John McCalld226f652010-08-21 09:40:31 +00005931Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005932 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005933 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005934 SourceLocation IdentLoc,
5935 IdentifierInfo *II,
5936 SourceLocation LBrace,
5937 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005938 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5939 // For anonymous namespace, take the location of the left brace.
5940 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005941 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005942 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005943 bool IsStd = false;
5944 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005945 Scope *DeclRegionScope = NamespcScope->getParent();
5946
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005947 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005948 if (II) {
5949 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005950 // The identifier in an original-namespace-definition shall not
5951 // have been previously defined in the declarative region in
5952 // which the original-namespace-definition appears. The
5953 // identifier in an original-namespace-definition is the name of
5954 // the namespace. Subsequently in that declarative region, it is
5955 // treated as an original-namespace-name.
5956 //
5957 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005958 // look through using directives, just look for any ordinary names.
5959
5960 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005961 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5962 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005963 NamedDecl *PrevDecl = 0;
5964 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005965 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005966 R.first != R.second; ++R.first) {
5967 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5968 PrevDecl = *R.first;
5969 break;
5970 }
5971 }
5972
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005973 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5974
5975 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005976 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00005977 if (IsInline != PrevNS->isInline())
5978 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
5979 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00005980 } else if (PrevDecl) {
5981 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005982 Diag(Loc, diag::err_redefinition_different_kind)
5983 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005984 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005985 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005986 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005987 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005988 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005989 // This is the first "real" definition of the namespace "std", so update
5990 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005991 PrevNS = getStdNamespace();
5992 IsStd = true;
5993 AddToKnown = !IsInline;
5994 } else {
5995 // We've seen this namespace for the first time.
5996 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005997 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005998 } else {
John McCall9aeed322009-10-01 00:25:31 +00005999 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006000
6001 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006002 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006003 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006004 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006005 } else {
6006 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006007 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006008 }
6009
Richard Smithd1a55a62012-10-04 22:13:39 +00006010 if (PrevNS && IsInline != PrevNS->isInline())
6011 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6012 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006013 }
6014
6015 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6016 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006017 if (IsInvalid)
6018 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006019
6020 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006021
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006022 // FIXME: Should we be merging attributes?
6023 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006024 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006025
6026 if (IsStd)
6027 StdNamespace = Namespc;
6028 if (AddToKnown)
6029 KnownNamespaces[Namespc] = false;
6030
6031 if (II) {
6032 PushOnScopeChains(Namespc, DeclRegionScope);
6033 } else {
6034 // Link the anonymous namespace into its parent.
6035 DeclContext *Parent = CurContext->getRedeclContext();
6036 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6037 TU->setAnonymousNamespace(Namespc);
6038 } else {
6039 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006040 }
John McCall9aeed322009-10-01 00:25:31 +00006041
Douglas Gregora4181472010-03-24 00:46:35 +00006042 CurContext->addDecl(Namespc);
6043
John McCall9aeed322009-10-01 00:25:31 +00006044 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6045 // behaves as if it were replaced by
6046 // namespace unique { /* empty body */ }
6047 // using namespace unique;
6048 // namespace unique { namespace-body }
6049 // where all occurrences of 'unique' in a translation unit are
6050 // replaced by the same identifier and this identifier differs
6051 // from all other identifiers in the entire program.
6052
6053 // We just create the namespace with an empty name and then add an
6054 // implicit using declaration, just like the standard suggests.
6055 //
6056 // CodeGen enforces the "universally unique" aspect by giving all
6057 // declarations semantically contained within an anonymous
6058 // namespace internal linkage.
6059
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006060 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006061 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006062 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006063 /* 'using' */ LBrace,
6064 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006065 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006066 /* identifier */ SourceLocation(),
6067 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006068 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006069 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006070 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006071 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006072 }
6073
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006074 ActOnDocumentableDecl(Namespc);
6075
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006076 // Although we could have an invalid decl (i.e. the namespace name is a
6077 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006078 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6079 // for the namespace has the declarations that showed up in that particular
6080 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006081 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006082 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006083}
6084
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006085/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6086/// is a namespace alias, returns the namespace it points to.
6087static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6088 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6089 return AD->getNamespace();
6090 return dyn_cast_or_null<NamespaceDecl>(D);
6091}
6092
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006093/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6094/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006095void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006096 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6097 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006098 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006099 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006100 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006101 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006102}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006103
John McCall384aff82010-08-25 07:42:41 +00006104CXXRecordDecl *Sema::getStdBadAlloc() const {
6105 return cast_or_null<CXXRecordDecl>(
6106 StdBadAlloc.get(Context.getExternalSource()));
6107}
6108
6109NamespaceDecl *Sema::getStdNamespace() const {
6110 return cast_or_null<NamespaceDecl>(
6111 StdNamespace.get(Context.getExternalSource()));
6112}
6113
Douglas Gregor66992202010-06-29 17:53:46 +00006114/// \brief Retrieve the special "std" namespace, which may require us to
6115/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006116NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006117 if (!StdNamespace) {
6118 // The "std" namespace has not yet been defined, so build one implicitly.
6119 StdNamespace = NamespaceDecl::Create(Context,
6120 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006121 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006122 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006123 &PP.getIdentifierTable().get("std"),
6124 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006125 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006126 }
6127
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006128 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006129}
6130
Sebastian Redl395e04d2012-01-17 22:49:33 +00006131bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006132 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006133 "Looking for std::initializer_list outside of C++.");
6134
6135 // We're looking for implicit instantiations of
6136 // template <typename E> class std::initializer_list.
6137
6138 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6139 return false;
6140
Sebastian Redl84760e32012-01-17 22:49:58 +00006141 ClassTemplateDecl *Template = 0;
6142 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006143
Sebastian Redl84760e32012-01-17 22:49:58 +00006144 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006145
Sebastian Redl84760e32012-01-17 22:49:58 +00006146 ClassTemplateSpecializationDecl *Specialization =
6147 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6148 if (!Specialization)
6149 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006150
Sebastian Redl84760e32012-01-17 22:49:58 +00006151 Template = Specialization->getSpecializedTemplate();
6152 Arguments = Specialization->getTemplateArgs().data();
6153 } else if (const TemplateSpecializationType *TST =
6154 Ty->getAs<TemplateSpecializationType>()) {
6155 Template = dyn_cast_or_null<ClassTemplateDecl>(
6156 TST->getTemplateName().getAsTemplateDecl());
6157 Arguments = TST->getArgs();
6158 }
6159 if (!Template)
6160 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006161
6162 if (!StdInitializerList) {
6163 // Haven't recognized std::initializer_list yet, maybe this is it.
6164 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6165 if (TemplateClass->getIdentifier() !=
6166 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006167 !getStdNamespace()->InEnclosingNamespaceSetOf(
6168 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006169 return false;
6170 // This is a template called std::initializer_list, but is it the right
6171 // template?
6172 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006173 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006174 return false;
6175 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6176 return false;
6177
6178 // It's the right template.
6179 StdInitializerList = Template;
6180 }
6181
6182 if (Template != StdInitializerList)
6183 return false;
6184
6185 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006186 if (Element)
6187 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006188 return true;
6189}
6190
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006191static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6192 NamespaceDecl *Std = S.getStdNamespace();
6193 if (!Std) {
6194 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6195 return 0;
6196 }
6197
6198 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6199 Loc, Sema::LookupOrdinaryName);
6200 if (!S.LookupQualifiedName(Result, Std)) {
6201 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6202 return 0;
6203 }
6204 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6205 if (!Template) {
6206 Result.suppressDiagnostics();
6207 // We found something weird. Complain about the first thing we found.
6208 NamedDecl *Found = *Result.begin();
6209 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6210 return 0;
6211 }
6212
6213 // We found some template called std::initializer_list. Now verify that it's
6214 // correct.
6215 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006216 if (Params->getMinRequiredArguments() != 1 ||
6217 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006218 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6219 return 0;
6220 }
6221
6222 return Template;
6223}
6224
6225QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6226 if (!StdInitializerList) {
6227 StdInitializerList = LookupStdInitializerList(*this, Loc);
6228 if (!StdInitializerList)
6229 return QualType();
6230 }
6231
6232 TemplateArgumentListInfo Args(Loc, Loc);
6233 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6234 Context.getTrivialTypeSourceInfo(Element,
6235 Loc)));
6236 return Context.getCanonicalType(
6237 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6238}
6239
Sebastian Redl98d36062012-01-17 22:50:14 +00006240bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6241 // C++ [dcl.init.list]p2:
6242 // A constructor is an initializer-list constructor if its first parameter
6243 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6244 // std::initializer_list<E> for some type E, and either there are no other
6245 // parameters or else all other parameters have default arguments.
6246 if (Ctor->getNumParams() < 1 ||
6247 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6248 return false;
6249
6250 QualType ArgType = Ctor->getParamDecl(0)->getType();
6251 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6252 ArgType = RT->getPointeeType().getUnqualifiedType();
6253
6254 return isStdInitializerList(ArgType, 0);
6255}
6256
Douglas Gregor9172aa62011-03-26 22:25:30 +00006257/// \brief Determine whether a using statement is in a context where it will be
6258/// apply in all contexts.
6259static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6260 switch (CurContext->getDeclKind()) {
6261 case Decl::TranslationUnit:
6262 return true;
6263 case Decl::LinkageSpec:
6264 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6265 default:
6266 return false;
6267 }
6268}
6269
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006270namespace {
6271
6272// Callback to only accept typo corrections that are namespaces.
6273class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6274 public:
6275 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6276 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6277 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6278 }
6279 return false;
6280 }
6281};
6282
6283}
6284
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006285static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6286 CXXScopeSpec &SS,
6287 SourceLocation IdentLoc,
6288 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006289 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006290 R.clear();
6291 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006292 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006293 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006294 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6295 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006296 if (DeclContext *DC = S.computeDeclContext(SS, false))
6297 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6298 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006299 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6300 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006301 else
6302 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6303 << Ident << CorrectedQuotedStr
6304 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006305
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006306 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6307 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006308
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006309 R.addDecl(Corrected.getCorrectionDecl());
6310 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006311 }
6312 return false;
6313}
6314
John McCalld226f652010-08-21 09:40:31 +00006315Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006316 SourceLocation UsingLoc,
6317 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006318 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006319 SourceLocation IdentLoc,
6320 IdentifierInfo *NamespcName,
6321 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006322 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6323 assert(NamespcName && "Invalid NamespcName.");
6324 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006325
6326 // This can only happen along a recovery path.
6327 while (S->getFlags() & Scope::TemplateParamScope)
6328 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006329 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006330
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006331 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006332 NestedNameSpecifier *Qualifier = 0;
6333 if (SS.isSet())
6334 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6335
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006336 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006337 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6338 LookupParsedName(R, S, &SS);
6339 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006340 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006341
Douglas Gregor66992202010-06-29 17:53:46 +00006342 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006343 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006344 // Allow "using namespace std;" or "using namespace ::std;" even if
6345 // "std" hasn't been defined yet, for GCC compatibility.
6346 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6347 NamespcName->isStr("std")) {
6348 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006349 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006350 R.resolveKind();
6351 }
6352 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006353 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006354 }
6355
John McCallf36e02d2009-10-09 21:13:30 +00006356 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006357 NamedDecl *Named = R.getFoundDecl();
6358 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6359 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006360 // C++ [namespace.udir]p1:
6361 // A using-directive specifies that the names in the nominated
6362 // namespace can be used in the scope in which the
6363 // using-directive appears after the using-directive. During
6364 // unqualified name lookup (3.4.1), the names appear as if they
6365 // were declared in the nearest enclosing namespace which
6366 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006367 // namespace. [Note: in this context, "contains" means "contains
6368 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006369
6370 // Find enclosing context containing both using-directive and
6371 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006372 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006373 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6374 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6375 CommonAncestor = CommonAncestor->getParent();
6376
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006377 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006378 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006379 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006380
Douglas Gregor9172aa62011-03-26 22:25:30 +00006381 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006382 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006383 Diag(IdentLoc, diag::warn_using_directive_in_header);
6384 }
6385
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006386 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006387 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006388 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006389 }
6390
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006391 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006392 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006393}
6394
6395void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006396 // If the scope has an associated entity and the using directive is at
6397 // namespace or translation unit scope, add the UsingDirectiveDecl into
6398 // its lookup structure so qualified name lookup can find it.
6399 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6400 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006401 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006402 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006403 // Otherwise, it is at block sope. The using-directives will affect lookup
6404 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006405 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006406}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006407
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006408
John McCalld226f652010-08-21 09:40:31 +00006409Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006410 AccessSpecifier AS,
6411 bool HasUsingKeyword,
6412 SourceLocation UsingLoc,
6413 CXXScopeSpec &SS,
6414 UnqualifiedId &Name,
6415 AttributeList *AttrList,
6416 bool IsTypeName,
6417 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006418 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006419
Douglas Gregor12c118a2009-11-04 16:30:06 +00006420 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006421 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006422 case UnqualifiedId::IK_Identifier:
6423 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006424 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006425 case UnqualifiedId::IK_ConversionFunctionId:
6426 break;
6427
6428 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006429 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006430 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006431 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006432 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006433 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6434 // instead once inheriting constructors work.
6435 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006436 diag::err_using_decl_constructor)
6437 << SS.getRange();
6438
David Blaikie4e4d0842012-03-11 07:00:24 +00006439 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00006440
John McCalld226f652010-08-21 09:40:31 +00006441 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006442
6443 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006444 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006445 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006446 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006447
6448 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006449 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006450 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006451 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006452 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006453
6454 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6455 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006456 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006457 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006458
John McCall60fa3cf2009-12-11 02:10:03 +00006459 // Warn about using declarations.
6460 // TODO: store that the declaration was written without 'using' and
6461 // talk about access decls instead of using decls in the
6462 // diagnostics.
6463 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006464 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006465
6466 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006467 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006468 }
6469
Douglas Gregor56c04582010-12-16 00:46:58 +00006470 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6471 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6472 return 0;
6473
John McCall9488ea12009-11-17 05:59:44 +00006474 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006475 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006476 /* IsInstantiation */ false,
6477 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006478 if (UD)
6479 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006480
John McCalld226f652010-08-21 09:40:31 +00006481 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006482}
6483
Douglas Gregor09acc982010-07-07 23:08:52 +00006484/// \brief Determine whether a using declaration considers the given
6485/// declarations as "equivalent", e.g., if they are redeclarations of
6486/// the same entity or are both typedefs of the same type.
6487static bool
6488IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6489 bool &SuppressRedeclaration) {
6490 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6491 SuppressRedeclaration = false;
6492 return true;
6493 }
6494
Richard Smith162e1c12011-04-15 14:24:37 +00006495 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6496 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006497 SuppressRedeclaration = true;
6498 return Context.hasSameType(TD1->getUnderlyingType(),
6499 TD2->getUnderlyingType());
6500 }
6501
6502 return false;
6503}
6504
6505
John McCall9f54ad42009-12-10 09:41:52 +00006506/// Determines whether to create a using shadow decl for a particular
6507/// decl, given the set of decls existing prior to this using lookup.
6508bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6509 const LookupResult &Previous) {
6510 // Diagnose finding a decl which is not from a base class of the
6511 // current class. We do this now because there are cases where this
6512 // function will silently decide not to build a shadow decl, which
6513 // will pre-empt further diagnostics.
6514 //
6515 // We don't need to do this in C++0x because we do the check once on
6516 // the qualifier.
6517 //
6518 // FIXME: diagnose the following if we care enough:
6519 // struct A { int foo; };
6520 // struct B : A { using A::foo; };
6521 // template <class T> struct C : A {};
6522 // template <class T> struct D : C<T> { using B::foo; } // <---
6523 // This is invalid (during instantiation) in C++03 because B::foo
6524 // resolves to the using decl in B, which is not a base class of D<T>.
6525 // We can't diagnose it immediately because C<T> is an unknown
6526 // specialization. The UsingShadowDecl in D<T> then points directly
6527 // to A::foo, which will look well-formed when we instantiate.
6528 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00006529 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006530 DeclContext *OrigDC = Orig->getDeclContext();
6531
6532 // Handle enums and anonymous structs.
6533 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6534 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6535 while (OrigRec->isAnonymousStructOrUnion())
6536 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6537
6538 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6539 if (OrigDC == CurContext) {
6540 Diag(Using->getLocation(),
6541 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006542 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006543 Diag(Orig->getLocation(), diag::note_using_decl_target);
6544 return true;
6545 }
6546
Douglas Gregordc355712011-02-25 00:36:19 +00006547 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006548 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006549 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006550 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006551 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006552 Diag(Orig->getLocation(), diag::note_using_decl_target);
6553 return true;
6554 }
6555 }
6556
6557 if (Previous.empty()) return false;
6558
6559 NamedDecl *Target = Orig;
6560 if (isa<UsingShadowDecl>(Target))
6561 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6562
John McCalld7533ec2009-12-11 02:33:26 +00006563 // If the target happens to be one of the previous declarations, we
6564 // don't have a conflict.
6565 //
6566 // FIXME: but we might be increasing its access, in which case we
6567 // should redeclare it.
6568 NamedDecl *NonTag = 0, *Tag = 0;
6569 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6570 I != E; ++I) {
6571 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006572 bool Result;
6573 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6574 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006575
6576 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6577 }
6578
John McCall9f54ad42009-12-10 09:41:52 +00006579 if (Target->isFunctionOrFunctionTemplate()) {
6580 FunctionDecl *FD;
6581 if (isa<FunctionTemplateDecl>(Target))
6582 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6583 else
6584 FD = cast<FunctionDecl>(Target);
6585
6586 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006587 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006588 case Ovl_Overload:
6589 return false;
6590
6591 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006592 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006593 break;
6594
6595 // We found a decl with the exact signature.
6596 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006597 // If we're in a record, we want to hide the target, so we
6598 // return true (without a diagnostic) to tell the caller not to
6599 // build a shadow decl.
6600 if (CurContext->isRecord())
6601 return true;
6602
6603 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006604 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006605 break;
6606 }
6607
6608 Diag(Target->getLocation(), diag::note_using_decl_target);
6609 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6610 return true;
6611 }
6612
6613 // Target is not a function.
6614
John McCall9f54ad42009-12-10 09:41:52 +00006615 if (isa<TagDecl>(Target)) {
6616 // No conflict between a tag and a non-tag.
6617 if (!Tag) return false;
6618
John McCall41ce66f2009-12-10 19:51:03 +00006619 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006620 Diag(Target->getLocation(), diag::note_using_decl_target);
6621 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6622 return true;
6623 }
6624
6625 // No conflict between a tag and a non-tag.
6626 if (!NonTag) return false;
6627
John McCall41ce66f2009-12-10 19:51:03 +00006628 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006629 Diag(Target->getLocation(), diag::note_using_decl_target);
6630 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6631 return true;
6632}
6633
John McCall9488ea12009-11-17 05:59:44 +00006634/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006635UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006636 UsingDecl *UD,
6637 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006638
6639 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006640 NamedDecl *Target = Orig;
6641 if (isa<UsingShadowDecl>(Target)) {
6642 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6643 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006644 }
6645
6646 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006647 = UsingShadowDecl::Create(Context, CurContext,
6648 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006649 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006650
6651 Shadow->setAccess(UD->getAccess());
6652 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6653 Shadow->setInvalidDecl();
6654
John McCall9488ea12009-11-17 05:59:44 +00006655 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006656 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006657 else
John McCall604e7f12009-12-08 07:46:18 +00006658 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006659
John McCall604e7f12009-12-08 07:46:18 +00006660
John McCall9f54ad42009-12-10 09:41:52 +00006661 return Shadow;
6662}
John McCall604e7f12009-12-08 07:46:18 +00006663
John McCall9f54ad42009-12-10 09:41:52 +00006664/// Hides a using shadow declaration. This is required by the current
6665/// using-decl implementation when a resolvable using declaration in a
6666/// class is followed by a declaration which would hide or override
6667/// one or more of the using decl's targets; for example:
6668///
6669/// struct Base { void foo(int); };
6670/// struct Derived : Base {
6671/// using Base::foo;
6672/// void foo(int);
6673/// };
6674///
6675/// The governing language is C++03 [namespace.udecl]p12:
6676///
6677/// When a using-declaration brings names from a base class into a
6678/// derived class scope, member functions in the derived class
6679/// override and/or hide member functions with the same name and
6680/// parameter types in a base class (rather than conflicting).
6681///
6682/// There are two ways to implement this:
6683/// (1) optimistically create shadow decls when they're not hidden
6684/// by existing declarations, or
6685/// (2) don't create any shadow decls (or at least don't make them
6686/// visible) until we've fully parsed/instantiated the class.
6687/// The problem with (1) is that we might have to retroactively remove
6688/// a shadow decl, which requires several O(n) operations because the
6689/// decl structures are (very reasonably) not designed for removal.
6690/// (2) avoids this but is very fiddly and phase-dependent.
6691void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006692 if (Shadow->getDeclName().getNameKind() ==
6693 DeclarationName::CXXConversionFunctionName)
6694 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6695
John McCall9f54ad42009-12-10 09:41:52 +00006696 // Remove it from the DeclContext...
6697 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006698
John McCall9f54ad42009-12-10 09:41:52 +00006699 // ...and the scope, if applicable...
6700 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006701 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006702 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006703 }
6704
John McCall9f54ad42009-12-10 09:41:52 +00006705 // ...and the using decl.
6706 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6707
6708 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006709 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006710}
6711
John McCall7ba107a2009-11-18 02:36:19 +00006712/// Builds a using declaration.
6713///
6714/// \param IsInstantiation - Whether this call arises from an
6715/// instantiation of an unresolved using declaration. We treat
6716/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006717NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6718 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006719 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006720 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006721 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006722 bool IsInstantiation,
6723 bool IsTypeName,
6724 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006725 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006726 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006727 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006728
Anders Carlsson550b14b2009-08-28 05:49:21 +00006729 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006730
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006731 if (SS.isEmpty()) {
6732 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006733 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006734 }
Mike Stump1eb44332009-09-09 15:08:12 +00006735
John McCall9f54ad42009-12-10 09:41:52 +00006736 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006737 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006738 ForRedeclaration);
6739 Previous.setHideTags(false);
6740 if (S) {
6741 LookupName(Previous, S);
6742
6743 // It is really dumb that we have to do this.
6744 LookupResult::Filter F = Previous.makeFilter();
6745 while (F.hasNext()) {
6746 NamedDecl *D = F.next();
6747 if (!isDeclInScope(D, CurContext, S))
6748 F.erase();
6749 }
6750 F.done();
6751 } else {
6752 assert(IsInstantiation && "no scope in non-instantiation");
6753 assert(CurContext->isRecord() && "scope not record in instantiation");
6754 LookupQualifiedName(Previous, CurContext);
6755 }
6756
John McCall9f54ad42009-12-10 09:41:52 +00006757 // Check for invalid redeclarations.
6758 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6759 return 0;
6760
6761 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006762 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6763 return 0;
6764
John McCallaf8e6ed2009-11-12 03:15:40 +00006765 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006766 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006767 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006768 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006769 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006770 // FIXME: not all declaration name kinds are legal here
6771 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6772 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006773 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006774 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006775 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006776 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6777 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006778 }
John McCalled976492009-12-04 22:46:56 +00006779 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006780 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6781 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006782 }
John McCalled976492009-12-04 22:46:56 +00006783 D->setAccess(AS);
6784 CurContext->addDecl(D);
6785
6786 if (!LookupContext) return D;
6787 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006788
John McCall77bb1aa2010-05-01 00:40:08 +00006789 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006790 UD->setInvalidDecl();
6791 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006792 }
6793
Richard Smithc5a89a12012-04-02 01:30:27 +00006794 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006795 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006796 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006797 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006798 return UD;
6799 }
6800
6801 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006802
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006803 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006804
John McCall604e7f12009-12-08 07:46:18 +00006805 // Unlike most lookups, we don't always want to hide tag
6806 // declarations: tag names are visible through the using declaration
6807 // even if hidden by ordinary names, *except* in a dependent context
6808 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006809 if (!IsInstantiation)
6810 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006811
John McCallb9abd8722012-04-07 03:04:20 +00006812 // For the purposes of this lookup, we have a base object type
6813 // equal to that of the current context.
6814 if (CurContext->isRecord()) {
6815 R.setBaseObjectType(
6816 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6817 }
6818
John McCalla24dc2e2009-11-17 02:14:36 +00006819 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006820
John McCallf36e02d2009-10-09 21:13:30 +00006821 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006822 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006823 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006824 UD->setInvalidDecl();
6825 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006826 }
6827
John McCalled976492009-12-04 22:46:56 +00006828 if (R.isAmbiguous()) {
6829 UD->setInvalidDecl();
6830 return UD;
6831 }
Mike Stump1eb44332009-09-09 15:08:12 +00006832
John McCall7ba107a2009-11-18 02:36:19 +00006833 if (IsTypeName) {
6834 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006835 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006836 Diag(IdentLoc, diag::err_using_typename_non_type);
6837 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6838 Diag((*I)->getUnderlyingDecl()->getLocation(),
6839 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006840 UD->setInvalidDecl();
6841 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006842 }
6843 } else {
6844 // If we asked for a non-typename and we got a type, error out,
6845 // but only if this is an instantiation of an unresolved using
6846 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006847 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006848 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6849 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006850 UD->setInvalidDecl();
6851 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006852 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006853 }
6854
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006855 // C++0x N2914 [namespace.udecl]p6:
6856 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006857 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006858 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6859 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006860 UD->setInvalidDecl();
6861 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006862 }
Mike Stump1eb44332009-09-09 15:08:12 +00006863
John McCall9f54ad42009-12-10 09:41:52 +00006864 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6865 if (!CheckUsingShadowDecl(UD, *I, Previous))
6866 BuildUsingShadowDecl(S, UD, *I);
6867 }
John McCall9488ea12009-11-17 05:59:44 +00006868
6869 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006870}
6871
Sebastian Redlf677ea32011-02-05 19:23:19 +00006872/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006873bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6874 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006875
Douglas Gregordc355712011-02-25 00:36:19 +00006876 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006877 assert(SourceType &&
6878 "Using decl naming constructor doesn't have type in scope spec.");
6879 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6880
6881 // Check whether the named type is a direct base class.
6882 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6883 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6884 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6885 BaseIt != BaseE; ++BaseIt) {
6886 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6887 if (CanonicalSourceType == BaseType)
6888 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006889 if (BaseIt->getType()->isDependentType())
6890 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006891 }
6892
6893 if (BaseIt == BaseE) {
6894 // Did not find SourceType in the bases.
6895 Diag(UD->getUsingLocation(),
6896 diag::err_using_decl_constructor_not_in_direct_base)
6897 << UD->getNameInfo().getSourceRange()
6898 << QualType(SourceType, 0) << TargetClass;
6899 return true;
6900 }
6901
Richard Smithc5a89a12012-04-02 01:30:27 +00006902 if (!CurContext->isDependentContext())
6903 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006904
6905 return false;
6906}
6907
John McCall9f54ad42009-12-10 09:41:52 +00006908/// Checks that the given using declaration is not an invalid
6909/// redeclaration. Note that this is checking only for the using decl
6910/// itself, not for any ill-formedness among the UsingShadowDecls.
6911bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6912 bool isTypeName,
6913 const CXXScopeSpec &SS,
6914 SourceLocation NameLoc,
6915 const LookupResult &Prev) {
6916 // C++03 [namespace.udecl]p8:
6917 // C++0x [namespace.udecl]p10:
6918 // A using-declaration is a declaration and can therefore be used
6919 // repeatedly where (and only where) multiple declarations are
6920 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006921 //
John McCall8a726212010-11-29 18:01:58 +00006922 // That's in non-member contexts.
6923 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006924 return false;
6925
6926 NestedNameSpecifier *Qual
6927 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6928
6929 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6930 NamedDecl *D = *I;
6931
6932 bool DTypename;
6933 NestedNameSpecifier *DQual;
6934 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6935 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006936 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006937 } else if (UnresolvedUsingValueDecl *UD
6938 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6939 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006940 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006941 } else if (UnresolvedUsingTypenameDecl *UD
6942 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6943 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006944 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006945 } else continue;
6946
6947 // using decls differ if one says 'typename' and the other doesn't.
6948 // FIXME: non-dependent using decls?
6949 if (isTypeName != DTypename) continue;
6950
6951 // using decls differ if they name different scopes (but note that
6952 // template instantiation can cause this check to trigger when it
6953 // didn't before instantiation).
6954 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6955 Context.getCanonicalNestedNameSpecifier(DQual))
6956 continue;
6957
6958 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006959 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006960 return true;
6961 }
6962
6963 return false;
6964}
6965
John McCall604e7f12009-12-08 07:46:18 +00006966
John McCalled976492009-12-04 22:46:56 +00006967/// Checks that the given nested-name qualifier used in a using decl
6968/// in the current context is appropriately related to the current
6969/// scope. If an error is found, diagnoses it and returns true.
6970bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6971 const CXXScopeSpec &SS,
6972 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006973 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006974
John McCall604e7f12009-12-08 07:46:18 +00006975 if (!CurContext->isRecord()) {
6976 // C++03 [namespace.udecl]p3:
6977 // C++0x [namespace.udecl]p8:
6978 // A using-declaration for a class member shall be a member-declaration.
6979
6980 // If we weren't able to compute a valid scope, it must be a
6981 // dependent class scope.
6982 if (!NamedContext || NamedContext->isRecord()) {
6983 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6984 << SS.getRange();
6985 return true;
6986 }
6987
6988 // Otherwise, everything is known to be fine.
6989 return false;
6990 }
6991
6992 // The current scope is a record.
6993
6994 // If the named context is dependent, we can't decide much.
6995 if (!NamedContext) {
6996 // FIXME: in C++0x, we can diagnose if we can prove that the
6997 // nested-name-specifier does not refer to a base class, which is
6998 // still possible in some cases.
6999
7000 // Otherwise we have to conservatively report that things might be
7001 // okay.
7002 return false;
7003 }
7004
7005 if (!NamedContext->isRecord()) {
7006 // Ideally this would point at the last name in the specifier,
7007 // but we don't have that level of source info.
7008 Diag(SS.getRange().getBegin(),
7009 diag::err_using_decl_nested_name_specifier_is_not_class)
7010 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7011 return true;
7012 }
7013
Douglas Gregor6fb07292010-12-21 07:41:49 +00007014 if (!NamedContext->isDependentContext() &&
7015 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7016 return true;
7017
David Blaikie4e4d0842012-03-11 07:00:24 +00007018 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00007019 // C++0x [namespace.udecl]p3:
7020 // In a using-declaration used as a member-declaration, the
7021 // nested-name-specifier shall name a base class of the class
7022 // being defined.
7023
7024 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7025 cast<CXXRecordDecl>(NamedContext))) {
7026 if (CurContext == NamedContext) {
7027 Diag(NameLoc,
7028 diag::err_using_decl_nested_name_specifier_is_current_class)
7029 << SS.getRange();
7030 return true;
7031 }
7032
7033 Diag(SS.getRange().getBegin(),
7034 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7035 << (NestedNameSpecifier*) SS.getScopeRep()
7036 << cast<CXXRecordDecl>(CurContext)
7037 << SS.getRange();
7038 return true;
7039 }
7040
7041 return false;
7042 }
7043
7044 // C++03 [namespace.udecl]p4:
7045 // A using-declaration used as a member-declaration shall refer
7046 // to a member of a base class of the class being defined [etc.].
7047
7048 // Salient point: SS doesn't have to name a base class as long as
7049 // lookup only finds members from base classes. Therefore we can
7050 // diagnose here only if we can prove that that can't happen,
7051 // i.e. if the class hierarchies provably don't intersect.
7052
7053 // TODO: it would be nice if "definitely valid" results were cached
7054 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7055 // need to be repeated.
7056
7057 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007058 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007059
7060 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7061 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7062 Data->Bases.insert(Base);
7063 return true;
7064 }
7065
7066 bool hasDependentBases(const CXXRecordDecl *Class) {
7067 return !Class->forallBases(collect, this);
7068 }
7069
7070 /// Returns true if the base is dependent or is one of the
7071 /// accumulated base classes.
7072 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7073 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7074 return !Data->Bases.count(Base);
7075 }
7076
7077 bool mightShareBases(const CXXRecordDecl *Class) {
7078 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7079 }
7080 };
7081
7082 UserData Data;
7083
7084 // Returns false if we find a dependent base.
7085 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7086 return false;
7087
7088 // Returns false if the class has a dependent base or if it or one
7089 // of its bases is present in the base set of the current context.
7090 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7091 return false;
7092
7093 Diag(SS.getRange().getBegin(),
7094 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7095 << (NestedNameSpecifier*) SS.getScopeRep()
7096 << cast<CXXRecordDecl>(CurContext)
7097 << SS.getRange();
7098
7099 return true;
John McCalled976492009-12-04 22:46:56 +00007100}
7101
Richard Smith162e1c12011-04-15 14:24:37 +00007102Decl *Sema::ActOnAliasDeclaration(Scope *S,
7103 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007104 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007105 SourceLocation UsingLoc,
7106 UnqualifiedId &Name,
7107 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007108 // Skip up to the relevant declaration scope.
7109 while (S->getFlags() & Scope::TemplateParamScope)
7110 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007111 assert((S->getFlags() & Scope::DeclScope) &&
7112 "got alias-declaration outside of declaration scope");
7113
7114 if (Type.isInvalid())
7115 return 0;
7116
7117 bool Invalid = false;
7118 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7119 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007120 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007121
7122 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7123 return 0;
7124
7125 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007126 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007127 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007128 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7129 TInfo->getTypeLoc().getBeginLoc());
7130 }
Richard Smith162e1c12011-04-15 14:24:37 +00007131
7132 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7133 LookupName(Previous, S);
7134
7135 // Warn about shadowing the name of a template parameter.
7136 if (Previous.isSingleResult() &&
7137 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007138 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007139 Previous.clear();
7140 }
7141
7142 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7143 "name in alias declaration must be an identifier");
7144 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7145 Name.StartLocation,
7146 Name.Identifier, TInfo);
7147
7148 NewTD->setAccess(AS);
7149
7150 if (Invalid)
7151 NewTD->setInvalidDecl();
7152
Richard Smith3e4c6c42011-05-05 21:57:07 +00007153 CheckTypedefForVariablyModifiedType(S, NewTD);
7154 Invalid |= NewTD->isInvalidDecl();
7155
Richard Smith162e1c12011-04-15 14:24:37 +00007156 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007157
7158 NamedDecl *NewND;
7159 if (TemplateParamLists.size()) {
7160 TypeAliasTemplateDecl *OldDecl = 0;
7161 TemplateParameterList *OldTemplateParams = 0;
7162
7163 if (TemplateParamLists.size() != 1) {
7164 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007165 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7166 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007167 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007168 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007169
7170 // Only consider previous declarations in the same scope.
7171 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7172 /*ExplicitInstantiationOrSpecialization*/false);
7173 if (!Previous.empty()) {
7174 Redeclaration = true;
7175
7176 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7177 if (!OldDecl && !Invalid) {
7178 Diag(UsingLoc, diag::err_redefinition_different_kind)
7179 << Name.Identifier;
7180
7181 NamedDecl *OldD = Previous.getRepresentativeDecl();
7182 if (OldD->getLocation().isValid())
7183 Diag(OldD->getLocation(), diag::note_previous_definition);
7184
7185 Invalid = true;
7186 }
7187
7188 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7189 if (TemplateParameterListsAreEqual(TemplateParams,
7190 OldDecl->getTemplateParameters(),
7191 /*Complain=*/true,
7192 TPL_TemplateMatch))
7193 OldTemplateParams = OldDecl->getTemplateParameters();
7194 else
7195 Invalid = true;
7196
7197 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7198 if (!Invalid &&
7199 !Context.hasSameType(OldTD->getUnderlyingType(),
7200 NewTD->getUnderlyingType())) {
7201 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7202 // but we can't reasonably accept it.
7203 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7204 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7205 if (OldTD->getLocation().isValid())
7206 Diag(OldTD->getLocation(), diag::note_previous_definition);
7207 Invalid = true;
7208 }
7209 }
7210 }
7211
7212 // Merge any previous default template arguments into our parameters,
7213 // and check the parameter list.
7214 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7215 TPC_TypeAliasTemplate))
7216 return 0;
7217
7218 TypeAliasTemplateDecl *NewDecl =
7219 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7220 Name.Identifier, TemplateParams,
7221 NewTD);
7222
7223 NewDecl->setAccess(AS);
7224
7225 if (Invalid)
7226 NewDecl->setInvalidDecl();
7227 else if (OldDecl)
7228 NewDecl->setPreviousDeclaration(OldDecl);
7229
7230 NewND = NewDecl;
7231 } else {
7232 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7233 NewND = NewTD;
7234 }
Richard Smith162e1c12011-04-15 14:24:37 +00007235
7236 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007237 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007238
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007239 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007240 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007241}
7242
John McCalld226f652010-08-21 09:40:31 +00007243Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007244 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007245 SourceLocation AliasLoc,
7246 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007247 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007248 SourceLocation IdentLoc,
7249 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007250
Anders Carlsson81c85c42009-03-28 23:53:49 +00007251 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007252 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7253 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007254
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007255 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007256 NamedDecl *PrevDecl
7257 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7258 ForRedeclaration);
7259 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7260 PrevDecl = 0;
7261
7262 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007263 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007264 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007265 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007266 // FIXME: At some point, we'll want to create the (redundant)
7267 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007268 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007269 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007270 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007271 }
Mike Stump1eb44332009-09-09 15:08:12 +00007272
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007273 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7274 diag::err_redefinition_different_kind;
7275 Diag(AliasLoc, DiagID) << Alias;
7276 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007277 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007278 }
7279
John McCalla24dc2e2009-11-17 02:14:36 +00007280 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007281 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007282
John McCallf36e02d2009-10-09 21:13:30 +00007283 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007284 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007285 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007286 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007287 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007288 }
Mike Stump1eb44332009-09-09 15:08:12 +00007289
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007290 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007291 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007292 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007293 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007294
John McCall3dbd3d52010-02-16 06:53:13 +00007295 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007296 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007297}
7298
Sean Hunt001cad92011-05-10 00:49:42 +00007299Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007300Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7301 CXXMethodDecl *MD) {
7302 CXXRecordDecl *ClassDecl = MD->getParent();
7303
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007304 // C++ [except.spec]p14:
7305 // An implicitly declared special member function (Clause 12) shall have an
7306 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007307 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007308 if (ClassDecl->isInvalidDecl())
7309 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007310
Sebastian Redl60618fa2011-03-12 11:50:43 +00007311 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007312 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7313 BEnd = ClassDecl->bases_end();
7314 B != BEnd; ++B) {
7315 if (B->isVirtual()) // Handled below.
7316 continue;
7317
Douglas Gregor18274032010-07-03 00:47:00 +00007318 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7319 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007320 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7321 // If this is a deleted function, add it anyway. This might be conformant
7322 // with the standard. This might not. I'm not sure. It might not matter.
7323 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007324 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007325 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007326 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007327
7328 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007329 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7330 BEnd = ClassDecl->vbases_end();
7331 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007332 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7333 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007334 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7335 // If this is a deleted function, add it anyway. This might be conformant
7336 // with the standard. This might not. I'm not sure. It might not matter.
7337 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007338 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007339 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007340 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007341
7342 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007343 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7344 FEnd = ClassDecl->field_end();
7345 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007346 if (F->hasInClassInitializer()) {
7347 if (Expr *E = F->getInClassInitializer())
7348 ExceptSpec.CalledExpr(E);
7349 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007350 // DR1351:
7351 // If the brace-or-equal-initializer of a non-static data member
7352 // invokes a defaulted default constructor of its class or of an
7353 // enclosing class in a potentially evaluated subexpression, the
7354 // program is ill-formed.
7355 //
7356 // This resolution is unworkable: the exception specification of the
7357 // default constructor can be needed in an unevaluated context, in
7358 // particular, in the operand of a noexcept-expression, and we can be
7359 // unable to compute an exception specification for an enclosed class.
7360 //
7361 // We do not allow an in-class initializer to require the evaluation
7362 // of the exception specification for any in-class initializer whose
7363 // definition is not lexically complete.
7364 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007365 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007366 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007367 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7368 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7369 // If this is a deleted function, add it anyway. This might be conformant
7370 // with the standard. This might not. I'm not sure. It might not matter.
7371 // In particular, the problem is that this function never gets called. It
7372 // might just be ill-formed because this function attempts to refer to
7373 // a deleted function here.
7374 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007375 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007376 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007377 }
John McCalle23cf432010-12-14 08:05:40 +00007378
Sean Hunt001cad92011-05-10 00:49:42 +00007379 return ExceptSpec;
7380}
7381
Richard Smithafb49182012-11-29 01:34:07 +00007382namespace {
7383/// RAII object to register a special member as being currently declared.
7384struct DeclaringSpecialMember {
7385 Sema &S;
7386 Sema::SpecialMemberDecl D;
7387 bool WasAlreadyBeingDeclared;
7388
7389 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7390 : S(S), D(RD, CSM) {
7391 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7392 if (WasAlreadyBeingDeclared)
7393 // This almost never happens, but if it does, ensure that our cache
7394 // doesn't contain a stale result.
7395 S.SpecialMemberCache.clear();
7396
7397 // FIXME: Register a note to be produced if we encounter an error while
7398 // declaring the special member.
7399 }
7400 ~DeclaringSpecialMember() {
7401 if (!WasAlreadyBeingDeclared)
7402 S.SpecialMembersBeingDeclared.erase(D);
7403 }
7404
7405 /// \brief Are we already trying to declare this special member?
7406 bool isAlreadyBeingDeclared() const {
7407 return WasAlreadyBeingDeclared;
7408 }
7409};
7410}
7411
Sean Hunt001cad92011-05-10 00:49:42 +00007412CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7413 CXXRecordDecl *ClassDecl) {
7414 // C++ [class.ctor]p5:
7415 // A default constructor for a class X is a constructor of class X
7416 // that can be called without an argument. If there is no
7417 // user-declared constructor for class X, a default constructor is
7418 // implicitly declared. An implicitly-declared default constructor
7419 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007420 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007421 "Should not build implicit default constructor!");
7422
Richard Smithafb49182012-11-29 01:34:07 +00007423 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7424 if (DSM.isAlreadyBeingDeclared())
7425 return 0;
7426
Richard Smith7756afa2012-06-10 05:43:50 +00007427 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7428 CXXDefaultConstructor,
7429 false);
7430
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007431 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007432 CanQualType ClassType
7433 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007434 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007435 DeclarationName Name
7436 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007437 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007438 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007439 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007440 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007441 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007442 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007443 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007444 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007445
7446 // Build an exception specification pointing back at this constructor.
7447 FunctionProtoType::ExtProtoInfo EPI;
7448 EPI.ExceptionSpecType = EST_Unevaluated;
7449 EPI.ExceptionSpecDecl = DefaultCon;
7450 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7451
Richard Smithbc2a35d2012-12-08 08:32:28 +00007452 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7453 // constructors is easy to compute.
7454 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7455
7456 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7457 DefaultCon->setDeletedAsWritten();
7458
Douglas Gregor18274032010-07-03 00:47:00 +00007459 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007460 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007461
Douglas Gregor23c94db2010-07-02 17:43:08 +00007462 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007463 PushOnScopeChains(DefaultCon, S, false);
7464 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007465
Douglas Gregor32df23e2010-07-01 22:02:46 +00007466 return DefaultCon;
7467}
7468
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007469void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7470 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007471 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007472 !Constructor->doesThisDeclarationHaveABody() &&
7473 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007474 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007475
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007476 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007477 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007478
Eli Friedman9a14db32012-10-18 20:14:08 +00007479 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007480 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007481 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007482 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007483 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007484 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007485 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007486 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007487 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007488
7489 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007490 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007491
7492 Constructor->setUsed();
7493 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007494
7495 if (ASTMutationListener *L = getASTMutationListener()) {
7496 L->CompletedImplicitDefinition(Constructor);
7497 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007498}
7499
Richard Smith7a614d82011-06-11 17:19:42 +00007500void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7501 if (!D) return;
7502 AdjustDeclIfTemplate(D);
7503
7504 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00007505
Richard Smithb9d0b762012-07-27 04:22:15 +00007506 if (!ClassDecl->isDependentType())
Richard Smithac713512012-12-08 02:53:02 +00007507 CheckExplicitlyDefaultedAndDeletedMethods(ClassDecl);
7508
7509 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
7510 // function that is not a constructor declares that member function to be
7511 // const. [...] The class of which that function is a member shall be
7512 // a literal type.
7513 //
7514 // If the class has virtual bases, any constexpr members will already have
7515 // been diagnosed by the checks performed on the member declaration, so
7516 // suppress this (less useful) diagnostic.
7517 //
7518 // We delay this until we know whether an explicitly-defaulted (or deleted)
7519 // destructor for the class is trivial.
7520 if (LangOpts.CPlusPlus0x && !ClassDecl->isDependentType() &&
7521 !ClassDecl->isLiteral() && !ClassDecl->getNumVBases()) {
7522 for (CXXRecordDecl::method_iterator M = ClassDecl->method_begin(),
7523 MEnd = ClassDecl->method_end();
7524 M != MEnd; ++M) {
7525 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
7526 switch (ClassDecl->getTemplateSpecializationKind()) {
7527 case TSK_ImplicitInstantiation:
7528 case TSK_ExplicitInstantiationDeclaration:
7529 case TSK_ExplicitInstantiationDefinition:
7530 // If a template instantiates to a non-literal type, but its members
7531 // instantiate to constexpr functions, the template is technically
7532 // ill-formed, but we allow it for sanity.
7533 continue;
7534
7535 case TSK_Undeclared:
7536 case TSK_ExplicitSpecialization:
7537 RequireLiteralType(M->getLocation(), Context.getRecordType(ClassDecl),
7538 diag::err_constexpr_method_non_literal);
7539 break;
7540 }
7541
7542 // Only produce one error per class.
7543 break;
7544 }
7545 }
7546 }
Richard Smith7a614d82011-06-11 17:19:42 +00007547}
7548
Sebastian Redlf677ea32011-02-05 19:23:19 +00007549void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7550 // We start with an initial pass over the base classes to collect those that
7551 // inherit constructors from. If there are none, we can forgo all further
7552 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007553 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007554 BasesVector BasesToInheritFrom;
7555 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7556 BaseE = ClassDecl->bases_end();
7557 BaseIt != BaseE; ++BaseIt) {
7558 if (BaseIt->getInheritConstructors()) {
7559 QualType Base = BaseIt->getType();
7560 if (Base->isDependentType()) {
7561 // If we inherit constructors from anything that is dependent, just
7562 // abort processing altogether. We'll get another chance for the
7563 // instantiations.
7564 return;
7565 }
7566 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7567 }
7568 }
7569 if (BasesToInheritFrom.empty())
7570 return;
7571
7572 // Now collect the constructors that we already have in the current class.
7573 // Those take precedence over inherited constructors.
7574 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7575 // unless there is a user-declared constructor with the same signature in
7576 // the class where the using-declaration appears.
7577 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7578 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7579 CtorE = ClassDecl->ctor_end();
7580 CtorIt != CtorE; ++CtorIt) {
7581 ExistingConstructors.insert(
7582 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7583 }
7584
Sebastian Redlf677ea32011-02-05 19:23:19 +00007585 DeclarationName CreatedCtorName =
7586 Context.DeclarationNames.getCXXConstructorName(
7587 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7588
7589 // Now comes the true work.
7590 // First, we keep a map from constructor types to the base that introduced
7591 // them. Needed for finding conflicting constructors. We also keep the
7592 // actually inserted declarations in there, for pretty diagnostics.
7593 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7594 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7595 ConstructorToSourceMap InheritedConstructors;
7596 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7597 BaseE = BasesToInheritFrom.end();
7598 BaseIt != BaseE; ++BaseIt) {
7599 const RecordType *Base = *BaseIt;
7600 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7601 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7602 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7603 CtorE = BaseDecl->ctor_end();
7604 CtorIt != CtorE; ++CtorIt) {
7605 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007606 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007607 DeclarationName Name =
7608 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007609 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7610 LookupQualifiedName(Result, CurContext);
7611 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007612 SourceLocation UsingLoc = UD ? UD->getLocation() :
7613 ClassDecl->getLocation();
7614
7615 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7616 // from the class X named in the using-declaration consists of actual
7617 // constructors and notional constructors that result from the
7618 // transformation of defaulted parameters as follows:
7619 // - all non-template default constructors of X, and
7620 // - for each non-template constructor of X that has at least one
7621 // parameter with a default argument, the set of constructors that
7622 // results from omitting any ellipsis parameter specification and
7623 // successively omitting parameters with a default argument from the
7624 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007625 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007626 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7627 const FunctionProtoType *BaseCtorType =
7628 BaseCtor->getType()->getAs<FunctionProtoType>();
7629
7630 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7631 maxParams = BaseCtor->getNumParams();
7632 params <= maxParams; ++params) {
7633 // Skip default constructors. They're never inherited.
7634 if (params == 0)
7635 continue;
7636 // Skip copy and move constructors for the same reason.
7637 if (CanBeCopyOrMove && params == 1)
7638 continue;
7639
7640 // Build up a function type for this particular constructor.
7641 // FIXME: The working paper does not consider that the exception spec
7642 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007643 // source. This code doesn't yet, either. When it does, this code will
7644 // need to be delayed until after exception specifications and in-class
7645 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007646 const Type *NewCtorType;
7647 if (params == maxParams)
7648 NewCtorType = BaseCtorType;
7649 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007650 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007651 for (unsigned i = 0; i < params; ++i) {
7652 Args.push_back(BaseCtorType->getArgType(i));
7653 }
7654 FunctionProtoType::ExtProtoInfo ExtInfo =
7655 BaseCtorType->getExtProtoInfo();
7656 ExtInfo.Variadic = false;
7657 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7658 Args.data(), params, ExtInfo)
7659 .getTypePtr();
7660 }
7661 const Type *CanonicalNewCtorType =
7662 Context.getCanonicalType(NewCtorType);
7663
7664 // Now that we have the type, first check if the class already has a
7665 // constructor with this signature.
7666 if (ExistingConstructors.count(CanonicalNewCtorType))
7667 continue;
7668
7669 // Then we check if we have already declared an inherited constructor
7670 // with this signature.
7671 std::pair<ConstructorToSourceMap::iterator, bool> result =
7672 InheritedConstructors.insert(std::make_pair(
7673 CanonicalNewCtorType,
7674 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7675 if (!result.second) {
7676 // Already in the map. If it came from a different class, that's an
7677 // error. Not if it's from the same.
7678 CanQualType PreviousBase = result.first->second.first;
7679 if (CanonicalBase != PreviousBase) {
7680 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7681 const CXXConstructorDecl *PrevBaseCtor =
7682 PrevCtor->getInheritedConstructor();
7683 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7684
7685 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7686 Diag(BaseCtor->getLocation(),
7687 diag::note_using_decl_constructor_conflict_current_ctor);
7688 Diag(PrevBaseCtor->getLocation(),
7689 diag::note_using_decl_constructor_conflict_previous_ctor);
7690 Diag(PrevCtor->getLocation(),
7691 diag::note_using_decl_constructor_conflict_previous_using);
7692 }
7693 continue;
7694 }
7695
7696 // OK, we're there, now add the constructor.
7697 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007698 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007699 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7700 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007701 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7702 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007703 /*ImplicitlyDeclared=*/true,
7704 // FIXME: Due to a defect in the standard, we treat inherited
7705 // constructors as constexpr even if that makes them ill-formed.
7706 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007707 NewCtor->setAccess(BaseCtor->getAccess());
7708
7709 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007710 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007711 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007712 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7713 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007714 /*IdentifierInfo=*/0,
7715 BaseCtorType->getArgType(i),
7716 /*TInfo=*/0, SC_None,
7717 SC_None, /*DefaultArg=*/0));
7718 }
David Blaikie4278c652011-09-21 18:16:56 +00007719 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007720 NewCtor->setInheritedConstructor(BaseCtor);
7721
Sebastian Redlf677ea32011-02-05 19:23:19 +00007722 ClassDecl->addDecl(NewCtor);
7723 result.first->second.second = NewCtor;
7724 }
7725 }
7726 }
7727}
7728
Sean Huntcb45a0f2011-05-12 22:46:25 +00007729Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007730Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7731 CXXRecordDecl *ClassDecl = MD->getParent();
7732
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007733 // C++ [except.spec]p14:
7734 // An implicitly declared special member function (Clause 12) shall have
7735 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007736 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007737 if (ClassDecl->isInvalidDecl())
7738 return ExceptSpec;
7739
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007740 // Direct base-class destructors.
7741 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7742 BEnd = ClassDecl->bases_end();
7743 B != BEnd; ++B) {
7744 if (B->isVirtual()) // Handled below.
7745 continue;
7746
7747 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007748 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007749 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007750 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007751
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007752 // Virtual base-class destructors.
7753 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7754 BEnd = ClassDecl->vbases_end();
7755 B != BEnd; ++B) {
7756 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007757 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007758 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007759 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007760
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007761 // Field destructors.
7762 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7763 FEnd = ClassDecl->field_end();
7764 F != FEnd; ++F) {
7765 if (const RecordType *RecordTy
7766 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007767 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007768 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007769 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007770
Sean Huntcb45a0f2011-05-12 22:46:25 +00007771 return ExceptSpec;
7772}
7773
7774CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7775 // C++ [class.dtor]p2:
7776 // If a class has no user-declared destructor, a destructor is
7777 // declared implicitly. An implicitly-declared destructor is an
7778 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007779 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007780
Richard Smithafb49182012-11-29 01:34:07 +00007781 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7782 if (DSM.isAlreadyBeingDeclared())
7783 return 0;
7784
Douglas Gregor4923aa22010-07-02 20:37:36 +00007785 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007786 CanQualType ClassType
7787 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007788 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007789 DeclarationName Name
7790 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007791 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007792 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007793 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7794 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007795 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007796 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007797 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007798 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007799
7800 // Build an exception specification pointing back at this destructor.
7801 FunctionProtoType::ExtProtoInfo EPI;
7802 EPI.ExceptionSpecType = EST_Unevaluated;
7803 EPI.ExceptionSpecDecl = Destructor;
7804 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7805
Richard Smithbc2a35d2012-12-08 08:32:28 +00007806 AddOverriddenMethods(ClassDecl, Destructor);
7807
7808 // We don't need to use SpecialMemberIsTrivial here; triviality for
7809 // destructors is easy to compute.
7810 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7811
7812 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7813 Destructor->setDeletedAsWritten();
7814
Douglas Gregor4923aa22010-07-02 20:37:36 +00007815 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007816 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007817
Douglas Gregor4923aa22010-07-02 20:37:36 +00007818 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007819 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007820 PushOnScopeChains(Destructor, S, false);
7821 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007822
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007823 return Destructor;
7824}
7825
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007826void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007827 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007828 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007829 !Destructor->doesThisDeclarationHaveABody() &&
7830 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007831 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007832 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007833 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007834
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007835 if (Destructor->isInvalidDecl())
7836 return;
7837
Eli Friedman9a14db32012-10-18 20:14:08 +00007838 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007839
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007840 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007841 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7842 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007843
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007844 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007845 Diag(CurrentLocation, diag::note_member_synthesized_at)
7846 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7847
7848 Destructor->setInvalidDecl();
7849 return;
7850 }
7851
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007852 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007853 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007854 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007855 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007856 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007857
7858 if (ASTMutationListener *L = getASTMutationListener()) {
7859 L->CompletedImplicitDefinition(Destructor);
7860 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007861}
7862
Richard Smitha4156b82012-04-21 18:42:51 +00007863/// \brief Perform any semantic analysis which needs to be delayed until all
7864/// pending class member declarations have been parsed.
7865void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007866 // Perform any deferred checking of exception specifications for virtual
7867 // destructors.
7868 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7869 i != e; ++i) {
7870 const CXXDestructorDecl *Dtor =
7871 DelayedDestructorExceptionSpecChecks[i].first;
7872 assert(!Dtor->getParent()->isDependentType() &&
7873 "Should not ever add destructors of templates into the list.");
7874 CheckOverridingFunctionExceptionSpec(Dtor,
7875 DelayedDestructorExceptionSpecChecks[i].second);
7876 }
7877 DelayedDestructorExceptionSpecChecks.clear();
7878}
7879
Richard Smithb9d0b762012-07-27 04:22:15 +00007880void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7881 CXXDestructorDecl *Destructor) {
7882 assert(getLangOpts().CPlusPlus0x &&
7883 "adjusting dtor exception specs was introduced in c++11");
7884
Sebastian Redl0ee33912011-05-19 05:13:44 +00007885 // C++11 [class.dtor]p3:
7886 // A declaration of a destructor that does not have an exception-
7887 // specification is implicitly considered to have the same exception-
7888 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007889 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007890 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007891 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007892 return;
7893
Chandler Carruth3f224b22011-09-20 04:55:26 +00007894 // Replace the destructor's type, building off the existing one. Fortunately,
7895 // the only thing of interest in the destructor type is its extended info.
7896 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007897 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7898 EPI.ExceptionSpecType = EST_Unevaluated;
7899 EPI.ExceptionSpecDecl = Destructor;
7900 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007901
Sebastian Redl0ee33912011-05-19 05:13:44 +00007902 // FIXME: If the destructor has a body that could throw, and the newly created
7903 // spec doesn't allow exceptions, we should emit a warning, because this
7904 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007905 // However, we don't have a body or an exception specification yet, so it
7906 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007907}
7908
Richard Smith8c889532012-11-14 00:50:40 +00007909/// When generating a defaulted copy or move assignment operator, if a field
7910/// should be copied with __builtin_memcpy rather than via explicit assignments,
7911/// do so. This optimization only applies for arrays of scalars, and for arrays
7912/// of class type where the selected copy/move-assignment operator is trivial.
7913static StmtResult
7914buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7915 Expr *To, Expr *From) {
7916 // Compute the size of the memory buffer to be copied.
7917 QualType SizeType = S.Context.getSizeType();
7918 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7919 S.Context.getTypeSizeInChars(T).getQuantity());
7920
7921 // Take the address of the field references for "from" and "to". We
7922 // directly construct UnaryOperators here because semantic analysis
7923 // does not permit us to take the address of an xvalue.
7924 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7925 S.Context.getPointerType(From->getType()),
7926 VK_RValue, OK_Ordinary, Loc);
7927 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7928 S.Context.getPointerType(To->getType()),
7929 VK_RValue, OK_Ordinary, Loc);
7930
7931 const Type *E = T->getBaseElementTypeUnsafe();
7932 bool NeedsCollectableMemCpy =
7933 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7934
7935 // Create a reference to the __builtin_objc_memmove_collectable function
7936 StringRef MemCpyName = NeedsCollectableMemCpy ?
7937 "__builtin_objc_memmove_collectable" :
7938 "__builtin_memcpy";
7939 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7940 Sema::LookupOrdinaryName);
7941 S.LookupName(R, S.TUScope, true);
7942
7943 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7944 if (!MemCpy)
7945 // Something went horribly wrong earlier, and we will have complained
7946 // about it.
7947 return StmtError();
7948
7949 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7950 VK_RValue, Loc, 0);
7951 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7952
7953 Expr *CallArgs[] = {
7954 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7955 };
7956 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7957 Loc, CallArgs, Loc);
7958
7959 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7960 return S.Owned(Call.takeAs<Stmt>());
7961}
7962
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007963/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007964/// \c To.
7965///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007966/// This routine is used to copy/move the members of a class with an
7967/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007968/// copied are arrays, this routine builds for loops to copy them.
7969///
7970/// \param S The Sema object used for type-checking.
7971///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007972/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007973///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007974/// \param T The type of the expressions being copied/moved. Both expressions
7975/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007976///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007977/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007978///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007979/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007980///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007981/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007982/// Otherwise, it's a non-static member subobject.
7983///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007984/// \param Copying Whether we're copying or moving.
7985///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007986/// \param Depth Internal parameter recording the depth of the recursion.
7987///
Richard Smith8c889532012-11-14 00:50:40 +00007988/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7989/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00007990static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00007991buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
7992 Expr *To, Expr *From,
7993 bool CopyingBaseSubobject, bool Copying,
7994 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00007995 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007996 // Each subobject is assigned in the manner appropriate to its type:
7997 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007998 // - if the subobject is of class type, as if by a call to operator= with
7999 // the subobject as the object expression and the corresponding
8000 // subobject of x as a single function argument (as if by explicit
8001 // qualification; that is, ignoring any possible virtual overriding
8002 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008003 //
8004 // C++03 [class.copy]p13:
8005 // - if the subobject is of class type, the copy assignment operator for
8006 // the class is used (as if by explicit qualification; that is,
8007 // ignoring any possible virtual overriding functions in more derived
8008 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008009 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8010 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008011
Douglas Gregor06a9f362010-05-01 20:49:11 +00008012 // Look for operator=.
8013 DeclarationName Name
8014 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8015 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8016 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008017
Richard Smith044c8aa2012-11-13 00:54:12 +00008018 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8019 // operator.
8020 if (!S.getLangOpts().CPlusPlus0x) {
8021 LookupResult::Filter F = OpLookup.makeFilter();
8022 while (F.hasNext()) {
8023 NamedDecl *D = F.next();
8024 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8025 if (Method->isCopyAssignmentOperator() ||
8026 (!Copying && Method->isMoveAssignmentOperator()))
8027 continue;
8028
8029 F.erase();
8030 }
8031 F.done();
John McCallb0207482010-03-16 06:11:48 +00008032 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008033
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008034 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008035 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008036 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008037 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008038 // ambiguities), we need to cast "this" to that subobject type; to
8039 // ensure that we don't go through the virtual call mechanism, we need
8040 // to qualify the operator= name with the base class (see below). However,
8041 // this means that if the base class has a protected copy assignment
8042 // operator, the protected member access check will fail. So, we
8043 // rewrite "protected" access to "public" access in this case, since we
8044 // know by construction that we're calling from a derived class.
8045 if (CopyingBaseSubobject) {
8046 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8047 L != LEnd; ++L) {
8048 if (L.getAccess() == AS_protected)
8049 L.setAccess(AS_public);
8050 }
8051 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008052
Douglas Gregor06a9f362010-05-01 20:49:11 +00008053 // Create the nested-name-specifier that will be used to qualify the
8054 // reference to operator=; this is required to suppress the virtual
8055 // call mechanism.
8056 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008057 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008058 SS.MakeTrivial(S.Context,
8059 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008060 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008061 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008062
Douglas Gregor06a9f362010-05-01 20:49:11 +00008063 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008064 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008065 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008066 /*TemplateKWLoc=*/SourceLocation(),
8067 /*FirstQualifierInScope=*/0,
8068 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008069 /*TemplateArgs=*/0,
8070 /*SuppressQualifierCheck=*/true);
8071 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008072 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008073
Douglas Gregor06a9f362010-05-01 20:49:11 +00008074 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008075
Richard Smith044c8aa2012-11-13 00:54:12 +00008076 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008077 OpEqualRef.takeAs<Expr>(),
8078 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008079 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008080 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008081
Richard Smith8c889532012-11-14 00:50:40 +00008082 // If we built a call to a trivial 'operator=' while copying an array,
8083 // bail out. We'll replace the whole shebang with a memcpy.
8084 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8085 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8086 return StmtResult((Stmt*)0);
8087
Richard Smith044c8aa2012-11-13 00:54:12 +00008088 // Convert to an expression-statement, and clean up any produced
8089 // temporaries.
8090 return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008091 }
John McCallb0207482010-03-16 06:11:48 +00008092
Richard Smith044c8aa2012-11-13 00:54:12 +00008093 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008094 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008095 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008096 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008097 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008098 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008099 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008100 return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008101 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008102
8103 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008104 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008105
Douglas Gregor06a9f362010-05-01 20:49:11 +00008106 // Construct a loop over the array bounds, e.g.,
8107 //
8108 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8109 //
8110 // that will copy each of the array elements.
8111 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008112
Douglas Gregor06a9f362010-05-01 20:49:11 +00008113 // Create the iteration variable.
8114 IdentifierInfo *IterationVarName = 0;
8115 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008116 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008117 llvm::raw_svector_ostream OS(Str);
8118 OS << "__i" << Depth;
8119 IterationVarName = &S.Context.Idents.get(OS.str());
8120 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008121 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008122 IterationVarName, SizeType,
8123 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008124 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008125
Douglas Gregor06a9f362010-05-01 20:49:11 +00008126 // Initialize the iteration variable to zero.
8127 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008128 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008129
8130 // Create a reference to the iteration variable; we'll use this several
8131 // times throughout.
8132 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008133 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008134 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008135 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8136 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8137
Douglas Gregor06a9f362010-05-01 20:49:11 +00008138 // Create the DeclStmt that holds the iteration variable.
8139 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008140
Douglas Gregor06a9f362010-05-01 20:49:11 +00008141 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008142 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008143 IterationVarRefRVal,
8144 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008145 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008146 IterationVarRefRVal,
8147 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008148 if (!Copying) // Cast to rvalue
8149 From = CastForMoving(S, From);
8150
8151 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008152 StmtResult Copy =
8153 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8154 To, From, CopyingBaseSubobject,
8155 Copying, Depth + 1);
8156 // Bail out if copying fails or if we determined that we should use memcpy.
8157 if (Copy.isInvalid() || !Copy.get())
8158 return Copy;
8159
8160 // Create the comparison against the array bound.
8161 llvm::APInt Upper
8162 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8163 Expr *Comparison
8164 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8165 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8166 BO_NE, S.Context.BoolTy,
8167 VK_RValue, OK_Ordinary, Loc, false);
8168
8169 // Create the pre-increment of the iteration variable.
8170 Expr *Increment
8171 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8172 VK_LValue, OK_Ordinary, Loc);
8173
Douglas Gregor06a9f362010-05-01 20:49:11 +00008174 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008175 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008176 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00008177 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008178 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008179}
8180
Richard Smith8c889532012-11-14 00:50:40 +00008181static StmtResult
8182buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8183 Expr *To, Expr *From,
8184 bool CopyingBaseSubobject, bool Copying) {
8185 // Maybe we should use a memcpy?
8186 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8187 T.isTriviallyCopyableType(S.Context))
8188 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8189
8190 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8191 CopyingBaseSubobject,
8192 Copying, 0));
8193
8194 // If we ended up picking a trivial assignment operator for an array of a
8195 // non-trivially-copyable class type, just emit a memcpy.
8196 if (!Result.isInvalid() && !Result.get())
8197 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8198
8199 return Result;
8200}
8201
Richard Smithb9d0b762012-07-27 04:22:15 +00008202Sema::ImplicitExceptionSpecification
8203Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8204 CXXRecordDecl *ClassDecl = MD->getParent();
8205
8206 ImplicitExceptionSpecification ExceptSpec(*this);
8207 if (ClassDecl->isInvalidDecl())
8208 return ExceptSpec;
8209
8210 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8211 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8212 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8213
Douglas Gregorb87786f2010-07-01 17:48:08 +00008214 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008215 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008216 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008217
8218 // It is unspecified whether or not an implicit copy assignment operator
8219 // attempts to deduplicate calls to assignment operators of virtual bases are
8220 // made. As such, this exception specification is effectively unspecified.
8221 // Based on a similar decision made for constness in C++0x, we're erring on
8222 // the side of assuming such calls to be made regardless of whether they
8223 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008224 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8225 BaseEnd = ClassDecl->bases_end();
8226 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008227 if (Base->isVirtual())
8228 continue;
8229
Douglas Gregora376d102010-07-02 21:50:04 +00008230 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008231 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008232 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8233 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008234 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008235 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008236
8237 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8238 BaseEnd = ClassDecl->vbases_end();
8239 Base != BaseEnd; ++Base) {
8240 CXXRecordDecl *BaseClassDecl
8241 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8242 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8243 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008244 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008245 }
8246
Douglas Gregorb87786f2010-07-01 17:48:08 +00008247 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8248 FieldEnd = ClassDecl->field_end();
8249 Field != FieldEnd;
8250 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008251 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008252 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8253 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008254 LookupCopyingAssignment(FieldClassDecl,
8255 ArgQuals | FieldType.getCVRQualifiers(),
8256 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008257 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008258 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008259 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008260
Richard Smithb9d0b762012-07-27 04:22:15 +00008261 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008262}
8263
8264CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8265 // Note: The following rules are largely analoguous to the copy
8266 // constructor rules. Note that virtual bases are not taken into account
8267 // for determining the argument type of the operator. Note also that
8268 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008269 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008270
Richard Smithafb49182012-11-29 01:34:07 +00008271 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8272 if (DSM.isAlreadyBeingDeclared())
8273 return 0;
8274
Sean Hunt30de05c2011-05-14 05:23:20 +00008275 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8276 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008277 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008278 ArgType = ArgType.withConst();
8279 ArgType = Context.getLValueReferenceType(ArgType);
8280
Douglas Gregord3c35902010-07-01 16:36:15 +00008281 // An implicitly-declared copy assignment operator is an inline public
8282 // member of its class.
8283 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008284 SourceLocation ClassLoc = ClassDecl->getLocation();
8285 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008286 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008287 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008288 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008289 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008290 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008291 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008292 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008293 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008294 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008295
8296 // Build an exception specification pointing back at this member.
8297 FunctionProtoType::ExtProtoInfo EPI;
8298 EPI.ExceptionSpecType = EST_Unevaluated;
8299 EPI.ExceptionSpecDecl = CopyAssignment;
8300 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8301
Douglas Gregord3c35902010-07-01 16:36:15 +00008302 // Add the parameter to the operator.
8303 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008304 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008305 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008306 SC_None,
8307 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008308 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008309
Richard Smithbc2a35d2012-12-08 08:32:28 +00008310 AddOverriddenMethods(ClassDecl, CopyAssignment);
8311
8312 CopyAssignment->setTrivial(
8313 ClassDecl->needsOverloadResolutionForCopyAssignment()
8314 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8315 : ClassDecl->hasTrivialCopyAssignment());
8316
Nico Weberafcc96a2012-01-23 03:19:29 +00008317 // C++0x [class.copy]p19:
8318 // .... If the class definition does not explicitly declare a copy
8319 // assignment operator, there is no user-declared move constructor, and
8320 // there is no user-declared move assignment operator, a copy assignment
8321 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008322 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008323 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008324
Richard Smithbc2a35d2012-12-08 08:32:28 +00008325 // Note that we have added this copy-assignment operator.
8326 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8327
8328 if (Scope *S = getScopeForContext(ClassDecl))
8329 PushOnScopeChains(CopyAssignment, S, false);
8330 ClassDecl->addDecl(CopyAssignment);
8331
Douglas Gregord3c35902010-07-01 16:36:15 +00008332 return CopyAssignment;
8333}
8334
Douglas Gregor06a9f362010-05-01 20:49:11 +00008335void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8336 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008337 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008338 CopyAssignOperator->isOverloadedOperator() &&
8339 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008340 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8341 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008342 "DefineImplicitCopyAssignment called for wrong function");
8343
8344 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8345
8346 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8347 CopyAssignOperator->setInvalidDecl();
8348 return;
8349 }
8350
8351 CopyAssignOperator->setUsed();
8352
Eli Friedman9a14db32012-10-18 20:14:08 +00008353 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008354 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008355
8356 // C++0x [class.copy]p30:
8357 // The implicitly-defined or explicitly-defaulted copy assignment operator
8358 // for a non-union class X performs memberwise copy assignment of its
8359 // subobjects. The direct base classes of X are assigned first, in the
8360 // order of their declaration in the base-specifier-list, and then the
8361 // immediate non-static data members of X are assigned, in the order in
8362 // which they were declared in the class definition.
8363
8364 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008365 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008366
8367 // The parameter for the "other" object, which we are copying from.
8368 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8369 Qualifiers OtherQuals = Other->getType().getQualifiers();
8370 QualType OtherRefType = Other->getType();
8371 if (const LValueReferenceType *OtherRef
8372 = OtherRefType->getAs<LValueReferenceType>()) {
8373 OtherRefType = OtherRef->getPointeeType();
8374 OtherQuals = OtherRefType.getQualifiers();
8375 }
8376
8377 // Our location for everything implicitly-generated.
8378 SourceLocation Loc = CopyAssignOperator->getLocation();
8379
8380 // Construct a reference to the "other" object. We'll be using this
8381 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008382 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008383 assert(OtherRef && "Reference to parameter cannot fail!");
8384
8385 // Construct the "this" pointer. We'll be using this throughout the generated
8386 // ASTs.
8387 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8388 assert(This && "Reference to this cannot fail!");
8389
8390 // Assign base classes.
8391 bool Invalid = false;
8392 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8393 E = ClassDecl->bases_end(); Base != E; ++Base) {
8394 // Form the assignment:
8395 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8396 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008397 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008398 Invalid = true;
8399 continue;
8400 }
8401
John McCallf871d0c2010-08-07 06:22:56 +00008402 CXXCastPath BasePath;
8403 BasePath.push_back(Base);
8404
Douglas Gregor06a9f362010-05-01 20:49:11 +00008405 // Construct the "from" expression, which is an implicit cast to the
8406 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008407 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008408 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8409 CK_UncheckedDerivedToBase,
8410 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008411
8412 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008413 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008414
8415 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008416 To = ImpCastExprToType(To.take(),
8417 Context.getCVRQualifiedType(BaseType,
8418 CopyAssignOperator->getTypeQualifiers()),
8419 CK_UncheckedDerivedToBase,
8420 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008421
8422 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008423 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008424 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008425 /*CopyingBaseSubobject=*/true,
8426 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008427 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008428 Diag(CurrentLocation, diag::note_member_synthesized_at)
8429 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8430 CopyAssignOperator->setInvalidDecl();
8431 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008432 }
8433
8434 // Success! Record the copy.
8435 Statements.push_back(Copy.takeAs<Expr>());
8436 }
8437
Douglas Gregor06a9f362010-05-01 20:49:11 +00008438 // Assign non-static members.
8439 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8440 FieldEnd = ClassDecl->field_end();
8441 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008442 if (Field->isUnnamedBitfield())
8443 continue;
8444
Douglas Gregor06a9f362010-05-01 20:49:11 +00008445 // Check for members of reference type; we can't copy those.
8446 if (Field->getType()->isReferenceType()) {
8447 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8448 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8449 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008450 Diag(CurrentLocation, diag::note_member_synthesized_at)
8451 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008452 Invalid = true;
8453 continue;
8454 }
8455
8456 // Check for members of const-qualified, non-class type.
8457 QualType BaseType = Context.getBaseElementType(Field->getType());
8458 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8459 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8460 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8461 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008462 Diag(CurrentLocation, diag::note_member_synthesized_at)
8463 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008464 Invalid = true;
8465 continue;
8466 }
John McCallb77115d2011-06-17 00:18:42 +00008467
8468 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008469 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8470 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008471
8472 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008473 if (FieldType->isIncompleteArrayType()) {
8474 assert(ClassDecl->hasFlexibleArrayMember() &&
8475 "Incomplete array type is not valid");
8476 continue;
8477 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008478
8479 // Build references to the field in the object we're copying from and to.
8480 CXXScopeSpec SS; // Intentionally empty
8481 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8482 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008483 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008484 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008485 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008486 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008487 SS, SourceLocation(), 0,
8488 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008489 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008490 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008491 SS, SourceLocation(), 0,
8492 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008493 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8494 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008495
Douglas Gregor06a9f362010-05-01 20:49:11 +00008496 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008497 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008498 To.get(), From.get(),
8499 /*CopyingBaseSubobject=*/false,
8500 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008501 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008502 Diag(CurrentLocation, diag::note_member_synthesized_at)
8503 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8504 CopyAssignOperator->setInvalidDecl();
8505 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008506 }
8507
8508 // Success! Record the copy.
8509 Statements.push_back(Copy.takeAs<Stmt>());
8510 }
8511
8512 if (!Invalid) {
8513 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008514 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008515
John McCall60d7b3a2010-08-24 06:29:42 +00008516 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008517 if (Return.isInvalid())
8518 Invalid = true;
8519 else {
8520 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008521
8522 if (Trap.hasErrorOccurred()) {
8523 Diag(CurrentLocation, diag::note_member_synthesized_at)
8524 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8525 Invalid = true;
8526 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008527 }
8528 }
8529
8530 if (Invalid) {
8531 CopyAssignOperator->setInvalidDecl();
8532 return;
8533 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008534
8535 StmtResult Body;
8536 {
8537 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008538 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008539 /*isStmtExpr=*/false);
8540 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8541 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008542 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008543
8544 if (ASTMutationListener *L = getASTMutationListener()) {
8545 L->CompletedImplicitDefinition(CopyAssignOperator);
8546 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008547}
8548
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008549Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008550Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8551 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008552
Richard Smithb9d0b762012-07-27 04:22:15 +00008553 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008554 if (ClassDecl->isInvalidDecl())
8555 return ExceptSpec;
8556
8557 // C++0x [except.spec]p14:
8558 // An implicitly declared special member function (Clause 12) shall have an
8559 // exception-specification. [...]
8560
8561 // It is unspecified whether or not an implicit move assignment operator
8562 // attempts to deduplicate calls to assignment operators of virtual bases are
8563 // made. As such, this exception specification is effectively unspecified.
8564 // Based on a similar decision made for constness in C++0x, we're erring on
8565 // the side of assuming such calls to be made regardless of whether they
8566 // actually happen.
8567 // Note that a move constructor is not implicitly declared when there are
8568 // virtual bases, but it can still be user-declared and explicitly defaulted.
8569 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8570 BaseEnd = ClassDecl->bases_end();
8571 Base != BaseEnd; ++Base) {
8572 if (Base->isVirtual())
8573 continue;
8574
8575 CXXRecordDecl *BaseClassDecl
8576 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8577 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008578 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008579 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008580 }
8581
8582 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8583 BaseEnd = ClassDecl->vbases_end();
8584 Base != BaseEnd; ++Base) {
8585 CXXRecordDecl *BaseClassDecl
8586 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8587 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008588 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008589 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008590 }
8591
8592 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8593 FieldEnd = ClassDecl->field_end();
8594 Field != FieldEnd;
8595 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008596 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008597 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008598 if (CXXMethodDecl *MoveAssign =
8599 LookupMovingAssignment(FieldClassDecl,
8600 FieldType.getCVRQualifiers(),
8601 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008602 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008603 }
8604 }
8605
8606 return ExceptSpec;
8607}
8608
Richard Smith1c931be2012-04-02 18:40:40 +00008609/// Determine whether the class type has any direct or indirect virtual base
8610/// classes which have a non-trivial move assignment operator.
8611static bool
8612hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8613 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8614 BaseEnd = ClassDecl->vbases_end();
8615 Base != BaseEnd; ++Base) {
8616 CXXRecordDecl *BaseClass =
8617 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8618
8619 // Try to declare the move assignment. If it would be deleted, then the
8620 // class does not have a non-trivial move assignment.
8621 if (BaseClass->needsImplicitMoveAssignment())
8622 S.DeclareImplicitMoveAssignment(BaseClass);
8623
Richard Smith426391c2012-11-16 00:53:38 +00008624 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008625 return true;
8626 }
8627
8628 return false;
8629}
8630
8631/// Determine whether the given type either has a move constructor or is
8632/// trivially copyable.
8633static bool
8634hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8635 Type = S.Context.getBaseElementType(Type);
8636
8637 // FIXME: Technically, non-trivially-copyable non-class types, such as
8638 // reference types, are supposed to return false here, but that appears
8639 // to be a standard defect.
8640 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008641 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008642 return true;
8643
8644 if (Type.isTriviallyCopyableType(S.Context))
8645 return true;
8646
8647 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008648 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8649 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008650 if (ClassDecl->needsImplicitMoveConstructor())
8651 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008652 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008653 }
8654
Richard Smithe5411b72012-12-01 02:35:44 +00008655 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8656 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008657 if (ClassDecl->needsImplicitMoveAssignment())
8658 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008659 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008660}
8661
8662/// Determine whether all non-static data members and direct or virtual bases
8663/// of class \p ClassDecl have either a move operation, or are trivially
8664/// copyable.
8665static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8666 bool IsConstructor) {
8667 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8668 BaseEnd = ClassDecl->bases_end();
8669 Base != BaseEnd; ++Base) {
8670 if (Base->isVirtual())
8671 continue;
8672
8673 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8674 return false;
8675 }
8676
8677 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8678 BaseEnd = ClassDecl->vbases_end();
8679 Base != BaseEnd; ++Base) {
8680 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8681 return false;
8682 }
8683
8684 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8685 FieldEnd = ClassDecl->field_end();
8686 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008687 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008688 return false;
8689 }
8690
8691 return true;
8692}
8693
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008694CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008695 // C++11 [class.copy]p20:
8696 // If the definition of a class X does not explicitly declare a move
8697 // assignment operator, one will be implicitly declared as defaulted
8698 // if and only if:
8699 //
8700 // - [first 4 bullets]
8701 assert(ClassDecl->needsImplicitMoveAssignment());
8702
Richard Smithafb49182012-11-29 01:34:07 +00008703 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8704 if (DSM.isAlreadyBeingDeclared())
8705 return 0;
8706
Richard Smith1c931be2012-04-02 18:40:40 +00008707 // [Checked after we build the declaration]
8708 // - the move assignment operator would not be implicitly defined as
8709 // deleted,
8710
8711 // [DR1402]:
8712 // - X has no direct or indirect virtual base class with a non-trivial
8713 // move assignment operator, and
8714 // - each of X's non-static data members and direct or virtual base classes
8715 // has a type that either has a move assignment operator or is trivially
8716 // copyable.
8717 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8718 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8719 ClassDecl->setFailedImplicitMoveAssignment();
8720 return 0;
8721 }
8722
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008723 // Note: The following rules are largely analoguous to the move
8724 // constructor rules.
8725
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008726 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8727 QualType RetType = Context.getLValueReferenceType(ArgType);
8728 ArgType = Context.getRValueReferenceType(ArgType);
8729
8730 // An implicitly-declared move assignment operator is an inline public
8731 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008732 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8733 SourceLocation ClassLoc = ClassDecl->getLocation();
8734 DeclarationNameInfo NameInfo(Name, ClassLoc);
8735 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008736 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008737 /*TInfo=*/0, /*isStatic=*/false,
8738 /*StorageClassAsWritten=*/SC_None,
8739 /*isInline=*/true,
8740 /*isConstexpr=*/false,
8741 SourceLocation());
8742 MoveAssignment->setAccess(AS_public);
8743 MoveAssignment->setDefaulted();
8744 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008745
Richard Smithb9d0b762012-07-27 04:22:15 +00008746 // Build an exception specification pointing back at this member.
8747 FunctionProtoType::ExtProtoInfo EPI;
8748 EPI.ExceptionSpecType = EST_Unevaluated;
8749 EPI.ExceptionSpecDecl = MoveAssignment;
8750 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8751
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008752 // Add the parameter to the operator.
8753 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8754 ClassLoc, ClassLoc, /*Id=*/0,
8755 ArgType, /*TInfo=*/0,
8756 SC_None,
8757 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008758 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008759
Richard Smithbc2a35d2012-12-08 08:32:28 +00008760 AddOverriddenMethods(ClassDecl, MoveAssignment);
8761
8762 MoveAssignment->setTrivial(
8763 ClassDecl->needsOverloadResolutionForMoveAssignment()
8764 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8765 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008766
8767 // C++0x [class.copy]p9:
8768 // If the definition of a class X does not explicitly declare a move
8769 // assignment operator, one will be implicitly declared as defaulted if and
8770 // only if:
8771 // [...]
8772 // - the move assignment operator would not be implicitly defined as
8773 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008774 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008775 // Cache this result so that we don't try to generate this over and over
8776 // on every lookup, leaking memory and wasting time.
8777 ClassDecl->setFailedImplicitMoveAssignment();
8778 return 0;
8779 }
8780
Richard Smithbc2a35d2012-12-08 08:32:28 +00008781 // Note that we have added this copy-assignment operator.
8782 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8783
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008784 if (Scope *S = getScopeForContext(ClassDecl))
8785 PushOnScopeChains(MoveAssignment, S, false);
8786 ClassDecl->addDecl(MoveAssignment);
8787
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008788 return MoveAssignment;
8789}
8790
8791void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8792 CXXMethodDecl *MoveAssignOperator) {
8793 assert((MoveAssignOperator->isDefaulted() &&
8794 MoveAssignOperator->isOverloadedOperator() &&
8795 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008796 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8797 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008798 "DefineImplicitMoveAssignment called for wrong function");
8799
8800 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8801
8802 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8803 MoveAssignOperator->setInvalidDecl();
8804 return;
8805 }
8806
8807 MoveAssignOperator->setUsed();
8808
Eli Friedman9a14db32012-10-18 20:14:08 +00008809 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008810 DiagnosticErrorTrap Trap(Diags);
8811
8812 // C++0x [class.copy]p28:
8813 // The implicitly-defined or move assignment operator for a non-union class
8814 // X performs memberwise move assignment of its subobjects. The direct base
8815 // classes of X are assigned first, in the order of their declaration in the
8816 // base-specifier-list, and then the immediate non-static data members of X
8817 // are assigned, in the order in which they were declared in the class
8818 // definition.
8819
8820 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008821 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008822
8823 // The parameter for the "other" object, which we are move from.
8824 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8825 QualType OtherRefType = Other->getType()->
8826 getAs<RValueReferenceType>()->getPointeeType();
8827 assert(OtherRefType.getQualifiers() == 0 &&
8828 "Bad argument type of defaulted move assignment");
8829
8830 // Our location for everything implicitly-generated.
8831 SourceLocation Loc = MoveAssignOperator->getLocation();
8832
8833 // Construct a reference to the "other" object. We'll be using this
8834 // throughout the generated ASTs.
8835 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8836 assert(OtherRef && "Reference to parameter cannot fail!");
8837 // Cast to rvalue.
8838 OtherRef = CastForMoving(*this, OtherRef);
8839
8840 // Construct the "this" pointer. We'll be using this throughout the generated
8841 // ASTs.
8842 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8843 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008844
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008845 // Assign base classes.
8846 bool Invalid = false;
8847 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8848 E = ClassDecl->bases_end(); Base != E; ++Base) {
8849 // Form the assignment:
8850 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8851 QualType BaseType = Base->getType().getUnqualifiedType();
8852 if (!BaseType->isRecordType()) {
8853 Invalid = true;
8854 continue;
8855 }
8856
8857 CXXCastPath BasePath;
8858 BasePath.push_back(Base);
8859
8860 // Construct the "from" expression, which is an implicit cast to the
8861 // appropriately-qualified base type.
8862 Expr *From = OtherRef;
8863 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008864 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008865
8866 // Dereference "this".
8867 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8868
8869 // Implicitly cast "this" to the appropriately-qualified base type.
8870 To = ImpCastExprToType(To.take(),
8871 Context.getCVRQualifiedType(BaseType,
8872 MoveAssignOperator->getTypeQualifiers()),
8873 CK_UncheckedDerivedToBase,
8874 VK_LValue, &BasePath);
8875
8876 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008877 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008878 To.get(), From,
8879 /*CopyingBaseSubobject=*/true,
8880 /*Copying=*/false);
8881 if (Move.isInvalid()) {
8882 Diag(CurrentLocation, diag::note_member_synthesized_at)
8883 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8884 MoveAssignOperator->setInvalidDecl();
8885 return;
8886 }
8887
8888 // Success! Record the move.
8889 Statements.push_back(Move.takeAs<Expr>());
8890 }
8891
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008892 // Assign non-static members.
8893 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8894 FieldEnd = ClassDecl->field_end();
8895 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008896 if (Field->isUnnamedBitfield())
8897 continue;
8898
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008899 // Check for members of reference type; we can't move those.
8900 if (Field->getType()->isReferenceType()) {
8901 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8902 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8903 Diag(Field->getLocation(), diag::note_declared_at);
8904 Diag(CurrentLocation, diag::note_member_synthesized_at)
8905 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8906 Invalid = true;
8907 continue;
8908 }
8909
8910 // Check for members of const-qualified, non-class type.
8911 QualType BaseType = Context.getBaseElementType(Field->getType());
8912 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8913 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8914 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8915 Diag(Field->getLocation(), diag::note_declared_at);
8916 Diag(CurrentLocation, diag::note_member_synthesized_at)
8917 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8918 Invalid = true;
8919 continue;
8920 }
8921
8922 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008923 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8924 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008925
8926 QualType FieldType = Field->getType().getNonReferenceType();
8927 if (FieldType->isIncompleteArrayType()) {
8928 assert(ClassDecl->hasFlexibleArrayMember() &&
8929 "Incomplete array type is not valid");
8930 continue;
8931 }
8932
8933 // Build references to the field in the object we're copying from and to.
8934 CXXScopeSpec SS; // Intentionally empty
8935 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8936 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008937 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008938 MemberLookup.resolveKind();
8939 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8940 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008941 SS, SourceLocation(), 0,
8942 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008943 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8944 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008945 SS, SourceLocation(), 0,
8946 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008947 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8948 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8949
8950 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8951 "Member reference with rvalue base must be rvalue except for reference "
8952 "members, which aren't allowed for move assignment.");
8953
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008954 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008955 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008956 To.get(), From.get(),
8957 /*CopyingBaseSubobject=*/false,
8958 /*Copying=*/false);
8959 if (Move.isInvalid()) {
8960 Diag(CurrentLocation, diag::note_member_synthesized_at)
8961 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8962 MoveAssignOperator->setInvalidDecl();
8963 return;
8964 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008965
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008966 // Success! Record the copy.
8967 Statements.push_back(Move.takeAs<Stmt>());
8968 }
8969
8970 if (!Invalid) {
8971 // Add a "return *this;"
8972 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8973
8974 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8975 if (Return.isInvalid())
8976 Invalid = true;
8977 else {
8978 Statements.push_back(Return.takeAs<Stmt>());
8979
8980 if (Trap.hasErrorOccurred()) {
8981 Diag(CurrentLocation, diag::note_member_synthesized_at)
8982 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8983 Invalid = true;
8984 }
8985 }
8986 }
8987
8988 if (Invalid) {
8989 MoveAssignOperator->setInvalidDecl();
8990 return;
8991 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008992
8993 StmtResult Body;
8994 {
8995 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008996 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008997 /*isStmtExpr=*/false);
8998 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8999 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009000 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9001
9002 if (ASTMutationListener *L = getASTMutationListener()) {
9003 L->CompletedImplicitDefinition(MoveAssignOperator);
9004 }
9005}
9006
Richard Smithb9d0b762012-07-27 04:22:15 +00009007Sema::ImplicitExceptionSpecification
9008Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9009 CXXRecordDecl *ClassDecl = MD->getParent();
9010
9011 ImplicitExceptionSpecification ExceptSpec(*this);
9012 if (ClassDecl->isInvalidDecl())
9013 return ExceptSpec;
9014
9015 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9016 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9017 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9018
Douglas Gregor0d405db2010-07-01 20:59:04 +00009019 // C++ [except.spec]p14:
9020 // An implicitly declared special member function (Clause 12) shall have an
9021 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009022 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9023 BaseEnd = ClassDecl->bases_end();
9024 Base != BaseEnd;
9025 ++Base) {
9026 // Virtual bases are handled below.
9027 if (Base->isVirtual())
9028 continue;
9029
Douglas Gregor22584312010-07-02 23:41:54 +00009030 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009031 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009032 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009033 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009034 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009035 }
9036 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9037 BaseEnd = ClassDecl->vbases_end();
9038 Base != BaseEnd;
9039 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009040 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009041 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009042 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009043 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009044 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009045 }
9046 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9047 FieldEnd = ClassDecl->field_end();
9048 Field != FieldEnd;
9049 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009050 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009051 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9052 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009053 LookupCopyingConstructor(FieldClassDecl,
9054 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009055 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009056 }
9057 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009058
Richard Smithb9d0b762012-07-27 04:22:15 +00009059 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009060}
9061
9062CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9063 CXXRecordDecl *ClassDecl) {
9064 // C++ [class.copy]p4:
9065 // If the class definition does not explicitly declare a copy
9066 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009067 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009068
Richard Smithafb49182012-11-29 01:34:07 +00009069 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9070 if (DSM.isAlreadyBeingDeclared())
9071 return 0;
9072
Sean Hunt49634cf2011-05-13 06:10:58 +00009073 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9074 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009075 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009076 if (Const)
9077 ArgType = ArgType.withConst();
9078 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009079
Richard Smith7756afa2012-06-10 05:43:50 +00009080 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9081 CXXCopyConstructor,
9082 Const);
9083
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009084 DeclarationName Name
9085 = Context.DeclarationNames.getCXXConstructorName(
9086 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009087 SourceLocation ClassLoc = ClassDecl->getLocation();
9088 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009089
9090 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009091 // member of its class.
9092 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009093 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009094 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009095 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009096 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009097 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009098
Richard Smithb9d0b762012-07-27 04:22:15 +00009099 // Build an exception specification pointing back at this member.
9100 FunctionProtoType::ExtProtoInfo EPI;
9101 EPI.ExceptionSpecType = EST_Unevaluated;
9102 EPI.ExceptionSpecDecl = CopyConstructor;
9103 CopyConstructor->setType(
9104 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9105
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009106 // Add the parameter to the constructor.
9107 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009108 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009109 /*IdentifierInfo=*/0,
9110 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009111 SC_None,
9112 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009113 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009114
Richard Smithbc2a35d2012-12-08 08:32:28 +00009115 CopyConstructor->setTrivial(
9116 ClassDecl->needsOverloadResolutionForCopyConstructor()
9117 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9118 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009119
Nico Weberafcc96a2012-01-23 03:19:29 +00009120 // C++11 [class.copy]p8:
9121 // ... If the class definition does not explicitly declare a copy
9122 // constructor, there is no user-declared move constructor, and there is no
9123 // user-declared move assignment operator, a copy constructor is implicitly
9124 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009125 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009126 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009127
Richard Smithbc2a35d2012-12-08 08:32:28 +00009128 // Note that we have declared this constructor.
9129 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9130
9131 if (Scope *S = getScopeForContext(ClassDecl))
9132 PushOnScopeChains(CopyConstructor, S, false);
9133 ClassDecl->addDecl(CopyConstructor);
9134
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009135 return CopyConstructor;
9136}
9137
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009138void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009139 CXXConstructorDecl *CopyConstructor) {
9140 assert((CopyConstructor->isDefaulted() &&
9141 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009142 !CopyConstructor->doesThisDeclarationHaveABody() &&
9143 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009144 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009145
Anders Carlsson63010a72010-04-23 16:24:12 +00009146 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009147 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009148
Eli Friedman9a14db32012-10-18 20:14:08 +00009149 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009150 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009151
Sean Huntcbb67482011-01-08 20:30:50 +00009152 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009153 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009154 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009155 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009156 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009157 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009158 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009159 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9160 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009161 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009162 /*isStmtExpr=*/false)
9163 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009164 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009165 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009166
9167 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009168 if (ASTMutationListener *L = getASTMutationListener()) {
9169 L->CompletedImplicitDefinition(CopyConstructor);
9170 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009171}
9172
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009173Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009174Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9175 CXXRecordDecl *ClassDecl = MD->getParent();
9176
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009177 // C++ [except.spec]p14:
9178 // An implicitly declared special member function (Clause 12) shall have an
9179 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009180 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009181 if (ClassDecl->isInvalidDecl())
9182 return ExceptSpec;
9183
9184 // Direct base-class constructors.
9185 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9186 BEnd = ClassDecl->bases_end();
9187 B != BEnd; ++B) {
9188 if (B->isVirtual()) // Handled below.
9189 continue;
9190
9191 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9192 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009193 CXXConstructorDecl *Constructor =
9194 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009195 // If this is a deleted function, add it anyway. This might be conformant
9196 // with the standard. This might not. I'm not sure. It might not matter.
9197 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009198 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009199 }
9200 }
9201
9202 // Virtual base-class constructors.
9203 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9204 BEnd = ClassDecl->vbases_end();
9205 B != BEnd; ++B) {
9206 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9207 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009208 CXXConstructorDecl *Constructor =
9209 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009210 // If this is a deleted function, add it anyway. This might be conformant
9211 // with the standard. This might not. I'm not sure. It might not matter.
9212 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009213 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009214 }
9215 }
9216
9217 // Field constructors.
9218 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9219 FEnd = ClassDecl->field_end();
9220 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009221 QualType FieldType = Context.getBaseElementType(F->getType());
9222 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9223 CXXConstructorDecl *Constructor =
9224 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009225 // If this is a deleted function, add it anyway. This might be conformant
9226 // with the standard. This might not. I'm not sure. It might not matter.
9227 // In particular, the problem is that this function never gets called. It
9228 // might just be ill-formed because this function attempts to refer to
9229 // a deleted function here.
9230 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009231 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009232 }
9233 }
9234
9235 return ExceptSpec;
9236}
9237
9238CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9239 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009240 // C++11 [class.copy]p9:
9241 // If the definition of a class X does not explicitly declare a move
9242 // constructor, one will be implicitly declared as defaulted if and only if:
9243 //
9244 // - [first 4 bullets]
9245 assert(ClassDecl->needsImplicitMoveConstructor());
9246
Richard Smithafb49182012-11-29 01:34:07 +00009247 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9248 if (DSM.isAlreadyBeingDeclared())
9249 return 0;
9250
Richard Smith1c931be2012-04-02 18:40:40 +00009251 // [Checked after we build the declaration]
9252 // - the move assignment operator would not be implicitly defined as
9253 // deleted,
9254
9255 // [DR1402]:
9256 // - each of X's non-static data members and direct or virtual base classes
9257 // has a type that either has a move constructor or is trivially copyable.
9258 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9259 ClassDecl->setFailedImplicitMoveConstructor();
9260 return 0;
9261 }
9262
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009263 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9264 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009265
Richard Smith7756afa2012-06-10 05:43:50 +00009266 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9267 CXXMoveConstructor,
9268 false);
9269
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009270 DeclarationName Name
9271 = Context.DeclarationNames.getCXXConstructorName(
9272 Context.getCanonicalType(ClassType));
9273 SourceLocation ClassLoc = ClassDecl->getLocation();
9274 DeclarationNameInfo NameInfo(Name, ClassLoc);
9275
9276 // C++0x [class.copy]p11:
9277 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009278 // member of its class.
9279 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009280 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009281 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009282 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009283 MoveConstructor->setAccess(AS_public);
9284 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009285
Richard Smithb9d0b762012-07-27 04:22:15 +00009286 // Build an exception specification pointing back at this member.
9287 FunctionProtoType::ExtProtoInfo EPI;
9288 EPI.ExceptionSpecType = EST_Unevaluated;
9289 EPI.ExceptionSpecDecl = MoveConstructor;
9290 MoveConstructor->setType(
9291 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9292
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009293 // Add the parameter to the constructor.
9294 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9295 ClassLoc, ClassLoc,
9296 /*IdentifierInfo=*/0,
9297 ArgType, /*TInfo=*/0,
9298 SC_None,
9299 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009300 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009301
Richard Smithbc2a35d2012-12-08 08:32:28 +00009302 MoveConstructor->setTrivial(
9303 ClassDecl->needsOverloadResolutionForMoveConstructor()
9304 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9305 : ClassDecl->hasTrivialMoveConstructor());
9306
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009307 // C++0x [class.copy]p9:
9308 // If the definition of a class X does not explicitly declare a move
9309 // constructor, one will be implicitly declared as defaulted if and only if:
9310 // [...]
9311 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009312 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009313 // Cache this result so that we don't try to generate this over and over
9314 // on every lookup, leaking memory and wasting time.
9315 ClassDecl->setFailedImplicitMoveConstructor();
9316 return 0;
9317 }
9318
9319 // Note that we have declared this constructor.
9320 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9321
9322 if (Scope *S = getScopeForContext(ClassDecl))
9323 PushOnScopeChains(MoveConstructor, S, false);
9324 ClassDecl->addDecl(MoveConstructor);
9325
9326 return MoveConstructor;
9327}
9328
9329void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9330 CXXConstructorDecl *MoveConstructor) {
9331 assert((MoveConstructor->isDefaulted() &&
9332 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009333 !MoveConstructor->doesThisDeclarationHaveABody() &&
9334 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009335 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9336
9337 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9338 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9339
Eli Friedman9a14db32012-10-18 20:14:08 +00009340 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009341 DiagnosticErrorTrap Trap(Diags);
9342
9343 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9344 Trap.hasErrorOccurred()) {
9345 Diag(CurrentLocation, diag::note_member_synthesized_at)
9346 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9347 MoveConstructor->setInvalidDecl();
9348 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009349 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009350 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9351 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009352 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009353 /*isStmtExpr=*/false)
9354 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009355 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009356 }
9357
9358 MoveConstructor->setUsed();
9359
9360 if (ASTMutationListener *L = getASTMutationListener()) {
9361 L->CompletedImplicitDefinition(MoveConstructor);
9362 }
9363}
9364
Douglas Gregore4e68d42012-02-15 19:33:52 +00009365bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9366 return FD->isDeleted() &&
9367 (FD->isDefaulted() || FD->isImplicit()) &&
9368 isa<CXXMethodDecl>(FD);
9369}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009370
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009371/// \brief Mark the call operator of the given lambda closure type as "used".
9372static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9373 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009374 = cast<CXXMethodDecl>(
9375 *Lambda->lookup(
9376 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009377 CallOperator->setReferenced();
9378 CallOperator->setUsed();
9379}
9380
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009381void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9382 SourceLocation CurrentLocation,
9383 CXXConversionDecl *Conv)
9384{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009385 CXXRecordDecl *Lambda = Conv->getParent();
9386
9387 // Make sure that the lambda call operator is marked used.
9388 markLambdaCallOperatorUsed(*this, Lambda);
9389
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009390 Conv->setUsed();
9391
Eli Friedman9a14db32012-10-18 20:14:08 +00009392 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009393 DiagnosticErrorTrap Trap(Diags);
9394
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009395 // Return the address of the __invoke function.
9396 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9397 CXXMethodDecl *Invoke
9398 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
9399 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9400 VK_LValue, Conv->getLocation()).take();
9401 assert(FunctionRef && "Can't refer to __invoke function?");
9402 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9403 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9404 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009405 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009406
9407 // Fill in the __invoke function with a dummy implementation. IR generation
9408 // will fill in the actual details.
9409 Invoke->setUsed();
9410 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009411 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009412
9413 if (ASTMutationListener *L = getASTMutationListener()) {
9414 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009415 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009416 }
9417}
9418
9419void Sema::DefineImplicitLambdaToBlockPointerConversion(
9420 SourceLocation CurrentLocation,
9421 CXXConversionDecl *Conv)
9422{
9423 Conv->setUsed();
9424
Eli Friedman9a14db32012-10-18 20:14:08 +00009425 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009426 DiagnosticErrorTrap Trap(Diags);
9427
Douglas Gregorac1303e2012-02-22 05:02:47 +00009428 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009429 Expr *This = ActOnCXXThis(CurrentLocation).take();
9430 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009431
Eli Friedman23f02672012-03-01 04:01:32 +00009432 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9433 Conv->getLocation(),
9434 Conv, DerefThis);
9435
9436 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9437 // behavior. Note that only the general conversion function does this
9438 // (since it's unusable otherwise); in the case where we inline the
9439 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009440 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009441 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9442 CK_CopyAndAutoreleaseBlockObject,
9443 BuildBlock.get(), 0, VK_RValue);
9444
9445 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009446 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009447 Conv->setInvalidDecl();
9448 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009449 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009450
Douglas Gregorac1303e2012-02-22 05:02:47 +00009451 // Create the return statement that returns the block from the conversion
9452 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009453 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009454 if (Return.isInvalid()) {
9455 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9456 Conv->setInvalidDecl();
9457 return;
9458 }
9459
9460 // Set the body of the conversion function.
9461 Stmt *ReturnS = Return.take();
9462 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9463 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009464 Conv->getLocation()));
9465
Douglas Gregorac1303e2012-02-22 05:02:47 +00009466 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009467 if (ASTMutationListener *L = getASTMutationListener()) {
9468 L->CompletedImplicitDefinition(Conv);
9469 }
9470}
9471
Douglas Gregorf52757d2012-03-10 06:53:13 +00009472/// \brief Determine whether the given list arguments contains exactly one
9473/// "real" (non-default) argument.
9474static bool hasOneRealArgument(MultiExprArg Args) {
9475 switch (Args.size()) {
9476 case 0:
9477 return false;
9478
9479 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009480 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009481 return false;
9482
9483 // fall through
9484 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009485 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009486 }
9487
9488 return false;
9489}
9490
John McCall60d7b3a2010-08-24 06:29:42 +00009491ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009492Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009493 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009494 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009495 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009496 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009497 unsigned ConstructKind,
9498 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009499 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009500
Douglas Gregor2f599792010-04-02 18:24:57 +00009501 // C++0x [class.copy]p34:
9502 // When certain criteria are met, an implementation is allowed to
9503 // omit the copy/move construction of a class object, even if the
9504 // copy/move constructor and/or destructor for the object have
9505 // side effects. [...]
9506 // - when a temporary class object that has not been bound to a
9507 // reference (12.2) would be copied/moved to a class object
9508 // with the same cv-unqualified type, the copy/move operation
9509 // can be omitted by constructing the temporary object
9510 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009511 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009512 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009513 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009514 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009515 }
Mike Stump1eb44332009-09-09 15:08:12 +00009516
9517 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009518 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009519 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009520}
9521
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009522/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9523/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009524ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009525Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9526 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009527 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009528 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009529 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009530 unsigned ConstructKind,
9531 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009532 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009533 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009534 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009535 HadMultipleCandidates, /*FIXME*/false,
9536 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009537 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9538 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009539}
9540
Mike Stump1eb44332009-09-09 15:08:12 +00009541bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009542 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009543 MultiExprArg Exprs,
9544 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009545 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009546 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009547 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009548 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009549 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009550 if (TempResult.isInvalid())
9551 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009552
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009553 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009554 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009555 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009556 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009557 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009558
Anders Carlssonfe2de492009-08-25 05:18:00 +00009559 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009560}
9561
John McCall68c6c9a2010-02-02 09:10:11 +00009562void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009563 if (VD->isInvalidDecl()) return;
9564
John McCall68c6c9a2010-02-02 09:10:11 +00009565 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009566 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009567 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009568 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009569
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009570 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009571 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009572 CheckDestructorAccess(VD->getLocation(), Destructor,
9573 PDiag(diag::err_access_dtor_var)
9574 << VD->getDeclName()
9575 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009576 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009577
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009578 if (!VD->hasGlobalStorage()) return;
9579
9580 // Emit warning for non-trivial dtor in global scope (a real global,
9581 // class-static, function-static).
9582 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9583
9584 // TODO: this should be re-enabled for static locals by !CXAAtExit
9585 if (!VD->isStaticLocal())
9586 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009587}
9588
Douglas Gregor39da0b82009-09-09 23:08:42 +00009589/// \brief Given a constructor and the set of arguments provided for the
9590/// constructor, convert the arguments and add any required default arguments
9591/// to form a proper call to this constructor.
9592///
9593/// \returns true if an error occurred, false otherwise.
9594bool
9595Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9596 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009597 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009598 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009599 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009600 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9601 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009602 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009603
9604 const FunctionProtoType *Proto
9605 = Constructor->getType()->getAs<FunctionProtoType>();
9606 assert(Proto && "Constructor without a prototype?");
9607 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009608
9609 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009610 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009611 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009612 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009613 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009614
9615 VariadicCallType CallType =
9616 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009617 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009618 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9619 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009620 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009621 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009622
9623 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9624
Richard Smith831421f2012-06-25 20:30:08 +00009625 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9626 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009627
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009628 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009629}
9630
Anders Carlsson20d45d22009-12-12 00:32:00 +00009631static inline bool
9632CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9633 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009634 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009635 if (isa<NamespaceDecl>(DC)) {
9636 return SemaRef.Diag(FnDecl->getLocation(),
9637 diag::err_operator_new_delete_declared_in_namespace)
9638 << FnDecl->getDeclName();
9639 }
9640
9641 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009642 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009643 return SemaRef.Diag(FnDecl->getLocation(),
9644 diag::err_operator_new_delete_declared_static)
9645 << FnDecl->getDeclName();
9646 }
9647
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009648 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009649}
9650
Anders Carlsson156c78e2009-12-13 17:53:43 +00009651static inline bool
9652CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9653 CanQualType ExpectedResultType,
9654 CanQualType ExpectedFirstParamType,
9655 unsigned DependentParamTypeDiag,
9656 unsigned InvalidParamTypeDiag) {
9657 QualType ResultType =
9658 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9659
9660 // Check that the result type is not dependent.
9661 if (ResultType->isDependentType())
9662 return SemaRef.Diag(FnDecl->getLocation(),
9663 diag::err_operator_new_delete_dependent_result_type)
9664 << FnDecl->getDeclName() << ExpectedResultType;
9665
9666 // Check that the result type is what we expect.
9667 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9668 return SemaRef.Diag(FnDecl->getLocation(),
9669 diag::err_operator_new_delete_invalid_result_type)
9670 << FnDecl->getDeclName() << ExpectedResultType;
9671
9672 // A function template must have at least 2 parameters.
9673 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9674 return SemaRef.Diag(FnDecl->getLocation(),
9675 diag::err_operator_new_delete_template_too_few_parameters)
9676 << FnDecl->getDeclName();
9677
9678 // The function decl must have at least 1 parameter.
9679 if (FnDecl->getNumParams() == 0)
9680 return SemaRef.Diag(FnDecl->getLocation(),
9681 diag::err_operator_new_delete_too_few_parameters)
9682 << FnDecl->getDeclName();
9683
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009684 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009685 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9686 if (FirstParamType->isDependentType())
9687 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9688 << FnDecl->getDeclName() << ExpectedFirstParamType;
9689
9690 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009691 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009692 ExpectedFirstParamType)
9693 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9694 << FnDecl->getDeclName() << ExpectedFirstParamType;
9695
9696 return false;
9697}
9698
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009699static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009700CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009701 // C++ [basic.stc.dynamic.allocation]p1:
9702 // A program is ill-formed if an allocation function is declared in a
9703 // namespace scope other than global scope or declared static in global
9704 // scope.
9705 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9706 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009707
9708 CanQualType SizeTy =
9709 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9710
9711 // C++ [basic.stc.dynamic.allocation]p1:
9712 // The return type shall be void*. The first parameter shall have type
9713 // std::size_t.
9714 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9715 SizeTy,
9716 diag::err_operator_new_dependent_param_type,
9717 diag::err_operator_new_param_type))
9718 return true;
9719
9720 // C++ [basic.stc.dynamic.allocation]p1:
9721 // The first parameter shall not have an associated default argument.
9722 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009723 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009724 diag::err_operator_new_default_arg)
9725 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9726
9727 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009728}
9729
9730static bool
Richard Smith444d3842012-10-20 08:26:51 +00009731CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009732 // C++ [basic.stc.dynamic.deallocation]p1:
9733 // A program is ill-formed if deallocation functions are declared in a
9734 // namespace scope other than global scope or declared static in global
9735 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009736 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9737 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009738
9739 // C++ [basic.stc.dynamic.deallocation]p2:
9740 // Each deallocation function shall return void and its first parameter
9741 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009742 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9743 SemaRef.Context.VoidPtrTy,
9744 diag::err_operator_delete_dependent_param_type,
9745 diag::err_operator_delete_param_type))
9746 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009747
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009748 return false;
9749}
9750
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009751/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9752/// of this overloaded operator is well-formed. If so, returns false;
9753/// otherwise, emits appropriate diagnostics and returns true.
9754bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009755 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009756 "Expected an overloaded operator declaration");
9757
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009758 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9759
Mike Stump1eb44332009-09-09 15:08:12 +00009760 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009761 // The allocation and deallocation functions, operator new,
9762 // operator new[], operator delete and operator delete[], are
9763 // described completely in 3.7.3. The attributes and restrictions
9764 // found in the rest of this subclause do not apply to them unless
9765 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009766 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009767 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009768
Anders Carlssona3ccda52009-12-12 00:26:23 +00009769 if (Op == OO_New || Op == OO_Array_New)
9770 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009771
9772 // C++ [over.oper]p6:
9773 // An operator function shall either be a non-static member
9774 // function or be a non-member function and have at least one
9775 // parameter whose type is a class, a reference to a class, an
9776 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009777 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9778 if (MethodDecl->isStatic())
9779 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009780 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009781 } else {
9782 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009783 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9784 ParamEnd = FnDecl->param_end();
9785 Param != ParamEnd; ++Param) {
9786 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009787 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9788 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009789 ClassOrEnumParam = true;
9790 break;
9791 }
9792 }
9793
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009794 if (!ClassOrEnumParam)
9795 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009796 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009797 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009798 }
9799
9800 // C++ [over.oper]p8:
9801 // An operator function cannot have default arguments (8.3.6),
9802 // except where explicitly stated below.
9803 //
Mike Stump1eb44332009-09-09 15:08:12 +00009804 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009805 // (C++ [over.call]p1).
9806 if (Op != OO_Call) {
9807 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9808 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009809 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009810 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009811 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009812 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009813 }
9814 }
9815
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009816 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9817 { false, false, false }
9818#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9819 , { Unary, Binary, MemberOnly }
9820#include "clang/Basic/OperatorKinds.def"
9821 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009822
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009823 bool CanBeUnaryOperator = OperatorUses[Op][0];
9824 bool CanBeBinaryOperator = OperatorUses[Op][1];
9825 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009826
9827 // C++ [over.oper]p8:
9828 // [...] Operator functions cannot have more or fewer parameters
9829 // than the number required for the corresponding operator, as
9830 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009831 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009832 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009833 if (Op != OO_Call &&
9834 ((NumParams == 1 && !CanBeUnaryOperator) ||
9835 (NumParams == 2 && !CanBeBinaryOperator) ||
9836 (NumParams < 1) || (NumParams > 2))) {
9837 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009838 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009839 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009840 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009841 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009842 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009843 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009844 assert(CanBeBinaryOperator &&
9845 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009846 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009847 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009848
Chris Lattner416e46f2008-11-21 07:57:12 +00009849 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009850 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009851 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009852
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009853 // Overloaded operators other than operator() cannot be variadic.
9854 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009855 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009856 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009857 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009858 }
9859
9860 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009861 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9862 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009863 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009864 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009865 }
9866
9867 // C++ [over.inc]p1:
9868 // The user-defined function called operator++ implements the
9869 // prefix and postfix ++ operator. If this function is a member
9870 // function with no parameters, or a non-member function with one
9871 // parameter of class or enumeration type, it defines the prefix
9872 // increment operator ++ for objects of that type. If the function
9873 // is a member function with one parameter (which shall be of type
9874 // int) or a non-member function with two parameters (the second
9875 // of which shall be of type int), it defines the postfix
9876 // increment operator ++ for objects of that type.
9877 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9878 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9879 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009880 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009881 ParamIsInt = BT->getKind() == BuiltinType::Int;
9882
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009883 if (!ParamIsInt)
9884 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009885 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009886 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009887 }
9888
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009889 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009890}
Chris Lattner5a003a42008-12-17 07:09:26 +00009891
Sean Hunta6c058d2010-01-13 09:01:02 +00009892/// CheckLiteralOperatorDeclaration - Check whether the declaration
9893/// of this literal operator function is well-formed. If so, returns
9894/// false; otherwise, emits appropriate diagnostics and returns true.
9895bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009896 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009897 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9898 << FnDecl->getDeclName();
9899 return true;
9900 }
9901
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009902 if (FnDecl->isExternC()) {
9903 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9904 return true;
9905 }
9906
Sean Hunta6c058d2010-01-13 09:01:02 +00009907 bool Valid = false;
9908
Richard Smith36f5cfe2012-03-09 08:00:36 +00009909 // This might be the definition of a literal operator template.
9910 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9911 // This might be a specialization of a literal operator template.
9912 if (!TpDecl)
9913 TpDecl = FnDecl->getPrimaryTemplate();
9914
Sean Hunt216c2782010-04-07 23:11:06 +00009915 // template <char...> type operator "" name() is the only valid template
9916 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009917 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009918 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009919 // Must have only one template parameter
9920 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9921 if (Params->size() == 1) {
9922 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009923 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009924
Sean Hunt216c2782010-04-07 23:11:06 +00009925 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009926 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9927 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9928 Valid = true;
9929 }
9930 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009931 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009932 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009933 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9934
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009935 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009936
Sean Hunt30019c02010-04-07 22:57:35 +00009937 // unsigned long long int, long double, and any character type are allowed
9938 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009939 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9940 Context.hasSameType(T, Context.LongDoubleTy) ||
9941 Context.hasSameType(T, Context.CharTy) ||
9942 Context.hasSameType(T, Context.WCharTy) ||
9943 Context.hasSameType(T, Context.Char16Ty) ||
9944 Context.hasSameType(T, Context.Char32Ty)) {
9945 if (++Param == FnDecl->param_end())
9946 Valid = true;
9947 goto FinishedParams;
9948 }
9949
Sean Hunt30019c02010-04-07 22:57:35 +00009950 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009951 const PointerType *PT = T->getAs<PointerType>();
9952 if (!PT)
9953 goto FinishedParams;
9954 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009955 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009956 goto FinishedParams;
9957 T = T.getUnqualifiedType();
9958
9959 // Move on to the second parameter;
9960 ++Param;
9961
9962 // If there is no second parameter, the first must be a const char *
9963 if (Param == FnDecl->param_end()) {
9964 if (Context.hasSameType(T, Context.CharTy))
9965 Valid = true;
9966 goto FinishedParams;
9967 }
9968
9969 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9970 // are allowed as the first parameter to a two-parameter function
9971 if (!(Context.hasSameType(T, Context.CharTy) ||
9972 Context.hasSameType(T, Context.WCharTy) ||
9973 Context.hasSameType(T, Context.Char16Ty) ||
9974 Context.hasSameType(T, Context.Char32Ty)))
9975 goto FinishedParams;
9976
9977 // The second and final parameter must be an std::size_t
9978 T = (*Param)->getType().getUnqualifiedType();
9979 if (Context.hasSameType(T, Context.getSizeType()) &&
9980 ++Param == FnDecl->param_end())
9981 Valid = true;
9982 }
9983
9984 // FIXME: This diagnostic is absolutely terrible.
9985FinishedParams:
9986 if (!Valid) {
9987 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9988 << FnDecl->getDeclName();
9989 return true;
9990 }
9991
Richard Smitha9e88b22012-03-09 08:16:22 +00009992 // A parameter-declaration-clause containing a default argument is not
9993 // equivalent to any of the permitted forms.
9994 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9995 ParamEnd = FnDecl->param_end();
9996 Param != ParamEnd; ++Param) {
9997 if ((*Param)->hasDefaultArg()) {
9998 Diag((*Param)->getDefaultArgRange().getBegin(),
9999 diag::err_literal_operator_default_argument)
10000 << (*Param)->getDefaultArgRange();
10001 break;
10002 }
10003 }
10004
Richard Smith2fb4ae32012-03-08 02:39:21 +000010005 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010006 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10007 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010008 // C++11 [usrlit.suffix]p1:
10009 // Literal suffix identifiers that do not start with an underscore
10010 // are reserved for future standardization.
10011 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010012 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010013
Sean Hunta6c058d2010-01-13 09:01:02 +000010014 return false;
10015}
10016
Douglas Gregor074149e2009-01-05 19:45:36 +000010017/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10018/// linkage specification, including the language and (if present)
10019/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10020/// the location of the language string literal, which is provided
10021/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10022/// the '{' brace. Otherwise, this linkage specification does not
10023/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010024Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10025 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010026 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010027 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010028 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010029 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010030 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010031 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010032 Language = LinkageSpecDecl::lang_cxx;
10033 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010034 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010035 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010036 }
Mike Stump1eb44332009-09-09 15:08:12 +000010037
Chris Lattnercc98eac2008-12-17 07:13:27 +000010038 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010039
Douglas Gregor074149e2009-01-05 19:45:36 +000010040 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010041 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010042 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010043 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010044 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010045}
10046
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010047/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010048/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10049/// valid, it's the position of the closing '}' brace in a linkage
10050/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010051Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010052 Decl *LinkageSpec,
10053 SourceLocation RBraceLoc) {
10054 if (LinkageSpec) {
10055 if (RBraceLoc.isValid()) {
10056 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10057 LSDecl->setRBraceLoc(RBraceLoc);
10058 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010059 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010060 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010061 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010062}
10063
Douglas Gregord308e622009-05-18 20:51:54 +000010064/// \brief Perform semantic analysis for the variable declaration that
10065/// occurs within a C++ catch clause, returning the newly-created
10066/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010067VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010068 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010069 SourceLocation StartLoc,
10070 SourceLocation Loc,
10071 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010072 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010073 QualType ExDeclType = TInfo->getType();
10074
Sebastian Redl4b07b292008-12-22 19:15:10 +000010075 // Arrays and functions decay.
10076 if (ExDeclType->isArrayType())
10077 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10078 else if (ExDeclType->isFunctionType())
10079 ExDeclType = Context.getPointerType(ExDeclType);
10080
10081 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10082 // The exception-declaration shall not denote a pointer or reference to an
10083 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010084 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010085 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010086 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010087 Invalid = true;
10088 }
Douglas Gregord308e622009-05-18 20:51:54 +000010089
Sebastian Redl4b07b292008-12-22 19:15:10 +000010090 QualType BaseType = ExDeclType;
10091 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010092 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010093 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010094 BaseType = Ptr->getPointeeType();
10095 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010096 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010097 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010098 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010099 BaseType = Ref->getPointeeType();
10100 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010101 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010102 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010103 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010104 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010105 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010106
Mike Stump1eb44332009-09-09 15:08:12 +000010107 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010108 RequireNonAbstractType(Loc, ExDeclType,
10109 diag::err_abstract_type_in_decl,
10110 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010111 Invalid = true;
10112
John McCall5a180392010-07-24 00:37:23 +000010113 // Only the non-fragile NeXT runtime currently supports C++ catches
10114 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010115 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010116 QualType T = ExDeclType;
10117 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10118 T = RT->getPointeeType();
10119
10120 if (T->isObjCObjectType()) {
10121 Diag(Loc, diag::err_objc_object_catch);
10122 Invalid = true;
10123 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010124 // FIXME: should this be a test for macosx-fragile specifically?
10125 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010126 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010127 }
10128 }
10129
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010130 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10131 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010132 ExDecl->setExceptionVariable(true);
10133
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010134 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010135 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010136 Invalid = true;
10137
Douglas Gregorc41b8782011-07-06 18:14:43 +000010138 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010139 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010140 // C++ [except.handle]p16:
10141 // The object declared in an exception-declaration or, if the
10142 // exception-declaration does not specify a name, a temporary (12.2) is
10143 // copy-initialized (8.5) from the exception object. [...]
10144 // The object is destroyed when the handler exits, after the destruction
10145 // of any automatic objects initialized within the handler.
10146 //
10147 // We just pretend to initialize the object with itself, then make sure
10148 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010149 QualType initType = ExDeclType;
10150
10151 InitializedEntity entity =
10152 InitializedEntity::InitializeVariable(ExDecl);
10153 InitializationKind initKind =
10154 InitializationKind::CreateCopy(Loc, SourceLocation());
10155
10156 Expr *opaqueValue =
10157 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10158 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10159 ExprResult result = sequence.Perform(*this, entity, initKind,
10160 MultiExprArg(&opaqueValue, 1));
10161 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010162 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010163 else {
10164 // If the constructor used was non-trivial, set this as the
10165 // "initializer".
10166 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10167 if (!construct->getConstructor()->isTrivial()) {
10168 Expr *init = MaybeCreateExprWithCleanups(construct);
10169 ExDecl->setInit(init);
10170 }
10171
10172 // And make sure it's destructable.
10173 FinalizeVarWithDestructor(ExDecl, recordType);
10174 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010175 }
10176 }
10177
Douglas Gregord308e622009-05-18 20:51:54 +000010178 if (Invalid)
10179 ExDecl->setInvalidDecl();
10180
10181 return ExDecl;
10182}
10183
10184/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10185/// handler.
John McCalld226f652010-08-21 09:40:31 +000010186Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010187 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010188 bool Invalid = D.isInvalidType();
10189
10190 // Check for unexpanded parameter packs.
10191 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10192 UPPC_ExceptionType)) {
10193 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10194 D.getIdentifierLoc());
10195 Invalid = true;
10196 }
10197
Sebastian Redl4b07b292008-12-22 19:15:10 +000010198 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010199 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010200 LookupOrdinaryName,
10201 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010202 // The scope should be freshly made just for us. There is just no way
10203 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010204 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010205 if (PrevDecl->isTemplateParameter()) {
10206 // Maybe we will complain about the shadowed template parameter.
10207 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010208 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010209 }
10210 }
10211
Chris Lattnereaaebc72009-04-25 08:06:05 +000010212 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010213 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10214 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010215 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010216 }
10217
Douglas Gregor83cb9422010-09-09 17:09:21 +000010218 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010219 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010220 D.getIdentifierLoc(),
10221 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010222 if (Invalid)
10223 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010224
Sebastian Redl4b07b292008-12-22 19:15:10 +000010225 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010226 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010227 PushOnScopeChains(ExDecl, S);
10228 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010229 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010230
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010231 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010232 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010233}
Anders Carlssonfb311762009-03-14 00:25:26 +000010234
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010235Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010236 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010237 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010238 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010239 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010240
Richard Smithe3f470a2012-07-11 22:37:56 +000010241 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10242 return 0;
10243
10244 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10245 AssertMessage, RParenLoc, false);
10246}
10247
10248Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10249 Expr *AssertExpr,
10250 StringLiteral *AssertMessage,
10251 SourceLocation RParenLoc,
10252 bool Failed) {
10253 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10254 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010255 // In a static_assert-declaration, the constant-expression shall be a
10256 // constant expression that can be contextually converted to bool.
10257 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10258 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010259 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010260
Richard Smithdaaefc52011-12-14 23:32:26 +000010261 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010262 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010263 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010264 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010265 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010266
Richard Smithe3f470a2012-07-11 22:37:56 +000010267 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +000010268 llvm::SmallString<256> MsgBuffer;
10269 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010270 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010271 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010272 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010273 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010274 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010275 }
Mike Stump1eb44332009-09-09 15:08:12 +000010276
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010277 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010278 AssertExpr, AssertMessage, RParenLoc,
10279 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010280
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010281 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010282 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010283}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010284
Douglas Gregor1d869352010-04-07 16:53:43 +000010285/// \brief Perform semantic analysis of the given friend type declaration.
10286///
10287/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010288FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010289 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010290 TypeSourceInfo *TSInfo) {
10291 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10292
10293 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010294 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010295
Richard Smith6b130222011-10-18 21:39:00 +000010296 // C++03 [class.friend]p2:
10297 // An elaborated-type-specifier shall be used in a friend declaration
10298 // for a class.*
10299 //
10300 // * The class-key of the elaborated-type-specifier is required.
10301 if (!ActiveTemplateInstantiations.empty()) {
10302 // Do not complain about the form of friend template types during
10303 // template instantiation; we will already have complained when the
10304 // template was declared.
10305 } else if (!T->isElaboratedTypeSpecifier()) {
10306 // If we evaluated the type to a record type, suggest putting
10307 // a tag in front.
10308 if (const RecordType *RT = T->getAs<RecordType>()) {
10309 RecordDecl *RD = RT->getDecl();
10310
10311 std::string InsertionText = std::string(" ") + RD->getKindName();
10312
10313 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010314 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010315 diag::warn_cxx98_compat_unelaborated_friend_type :
10316 diag::ext_unelaborated_friend_type)
10317 << (unsigned) RD->getTagKind()
10318 << T
10319 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10320 InsertionText);
10321 } else {
10322 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010323 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010324 diag::warn_cxx98_compat_nonclass_type_friend :
10325 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010326 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010327 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010328 }
Richard Smith6b130222011-10-18 21:39:00 +000010329 } else if (T->getAs<EnumType>()) {
10330 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010331 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010332 diag::warn_cxx98_compat_enum_friend :
10333 diag::ext_enum_friend)
10334 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010335 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010336 }
10337
Richard Smithd6f80da2012-09-20 01:31:00 +000010338 // C++11 [class.friend]p3:
10339 // A friend declaration that does not declare a function shall have one
10340 // of the following forms:
10341 // friend elaborated-type-specifier ;
10342 // friend simple-type-specifier ;
10343 // friend typename-specifier ;
10344 if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc)
10345 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10346
Douglas Gregor06245bf2010-04-07 17:57:12 +000010347 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010348 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010349 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010350 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010351}
10352
John McCall9a34edb2010-10-19 01:40:49 +000010353/// Handle a friend tag declaration where the scope specifier was
10354/// templated.
10355Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10356 unsigned TagSpec, SourceLocation TagLoc,
10357 CXXScopeSpec &SS,
10358 IdentifierInfo *Name, SourceLocation NameLoc,
10359 AttributeList *Attr,
10360 MultiTemplateParamsArg TempParamLists) {
10361 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10362
10363 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010364 bool Invalid = false;
10365
10366 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010367 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010368 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010369 TempParamLists.size(),
10370 /*friend*/ true,
10371 isExplicitSpecialization,
10372 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010373 if (TemplateParams->size() > 0) {
10374 // This is a declaration of a class template.
10375 if (Invalid)
10376 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010377
Eric Christopher4110e132011-07-21 05:34:24 +000010378 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10379 SS, Name, NameLoc, Attr,
10380 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010381 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010382 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010383 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010384 } else {
10385 // The "template<>" header is extraneous.
10386 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10387 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10388 isExplicitSpecialization = true;
10389 }
10390 }
10391
10392 if (Invalid) return 0;
10393
John McCall9a34edb2010-10-19 01:40:49 +000010394 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010395 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010396 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010397 isAllExplicitSpecializations = false;
10398 break;
10399 }
10400 }
10401
10402 // FIXME: don't ignore attributes.
10403
10404 // If it's explicit specializations all the way down, just forget
10405 // about the template header and build an appropriate non-templated
10406 // friend. TODO: for source fidelity, remember the headers.
10407 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010408 if (SS.isEmpty()) {
10409 bool Owned = false;
10410 bool IsDependent = false;
10411 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10412 Attr, AS_public,
10413 /*ModulePrivateLoc=*/SourceLocation(),
10414 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010415 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010416 /*ScopedEnumUsesClassTag=*/false,
10417 /*UnderlyingType=*/TypeResult());
10418 }
10419
Douglas Gregor2494dd02011-03-01 01:34:45 +000010420 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010421 ElaboratedTypeKeyword Keyword
10422 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010423 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010424 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010425 if (T.isNull())
10426 return 0;
10427
10428 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10429 if (isa<DependentNameType>(T)) {
10430 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010431 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010432 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010433 TL.setNameLoc(NameLoc);
10434 } else {
10435 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010436 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010437 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010438 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10439 }
10440
10441 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10442 TSI, FriendLoc);
10443 Friend->setAccess(AS_public);
10444 CurContext->addDecl(Friend);
10445 return Friend;
10446 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010447
10448 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10449
10450
John McCall9a34edb2010-10-19 01:40:49 +000010451
10452 // Handle the case of a templated-scope friend class. e.g.
10453 // template <class T> class A<T>::B;
10454 // FIXME: we don't support these right now.
10455 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10456 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10457 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10458 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010459 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010460 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010461 TL.setNameLoc(NameLoc);
10462
10463 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10464 TSI, FriendLoc);
10465 Friend->setAccess(AS_public);
10466 Friend->setUnsupportedFriend(true);
10467 CurContext->addDecl(Friend);
10468 return Friend;
10469}
10470
10471
John McCalldd4a3b02009-09-16 22:47:08 +000010472/// Handle a friend type declaration. This works in tandem with
10473/// ActOnTag.
10474///
10475/// Notes on friend class templates:
10476///
10477/// We generally treat friend class declarations as if they were
10478/// declaring a class. So, for example, the elaborated type specifier
10479/// in a friend declaration is required to obey the restrictions of a
10480/// class-head (i.e. no typedefs in the scope chain), template
10481/// parameters are required to match up with simple template-ids, &c.
10482/// However, unlike when declaring a template specialization, it's
10483/// okay to refer to a template specialization without an empty
10484/// template parameter declaration, e.g.
10485/// friend class A<T>::B<unsigned>;
10486/// We permit this as a special case; if there are any template
10487/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010488/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010489Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010490 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010491 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010492
10493 assert(DS.isFriendSpecified());
10494 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10495
John McCalldd4a3b02009-09-16 22:47:08 +000010496 // Try to convert the decl specifier to a type. This works for
10497 // friend templates because ActOnTag never produces a ClassTemplateDecl
10498 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010499 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010500 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10501 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010502 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010503 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010504
Douglas Gregor6ccab972010-12-16 01:14:37 +000010505 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10506 return 0;
10507
John McCalldd4a3b02009-09-16 22:47:08 +000010508 // This is definitely an error in C++98. It's probably meant to
10509 // be forbidden in C++0x, too, but the specification is just
10510 // poorly written.
10511 //
10512 // The problem is with declarations like the following:
10513 // template <T> friend A<T>::foo;
10514 // where deciding whether a class C is a friend or not now hinges
10515 // on whether there exists an instantiation of A that causes
10516 // 'foo' to equal C. There are restrictions on class-heads
10517 // (which we declare (by fiat) elaborated friend declarations to
10518 // be) that makes this tractable.
10519 //
10520 // FIXME: handle "template <> friend class A<T>;", which
10521 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010522 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010523 Diag(Loc, diag::err_tagless_friend_type_template)
10524 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010525 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010526 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010527
John McCall02cace72009-08-28 07:59:38 +000010528 // C++98 [class.friend]p1: A friend of a class is a function
10529 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010530 // This is fixed in DR77, which just barely didn't make the C++03
10531 // deadline. It's also a very silly restriction that seriously
10532 // affects inner classes and which nobody else seems to implement;
10533 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010534 //
10535 // But note that we could warn about it: it's always useless to
10536 // friend one of your own members (it's not, however, worthless to
10537 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010538
John McCalldd4a3b02009-09-16 22:47:08 +000010539 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010540 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010541 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010542 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010543 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010544 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010545 DS.getFriendSpecLoc());
10546 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010547 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010548
10549 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010550 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010551
John McCalldd4a3b02009-09-16 22:47:08 +000010552 D->setAccess(AS_public);
10553 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010554
John McCalld226f652010-08-21 09:40:31 +000010555 return D;
John McCall02cace72009-08-28 07:59:38 +000010556}
10557
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010558Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010559 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010560 const DeclSpec &DS = D.getDeclSpec();
10561
10562 assert(DS.isFriendSpecified());
10563 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10564
10565 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010566 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010567
10568 // C++ [class.friend]p1
10569 // A friend of a class is a function or class....
10570 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010571 // It *doesn't* see through dependent types, which is correct
10572 // according to [temp.arg.type]p3:
10573 // If a declaration acquires a function type through a
10574 // type dependent on a template-parameter and this causes
10575 // a declaration that does not use the syntactic form of a
10576 // function declarator to have a function type, the program
10577 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010578 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010579 Diag(Loc, diag::err_unexpected_friend);
10580
10581 // It might be worthwhile to try to recover by creating an
10582 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010583 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010584 }
10585
10586 // C++ [namespace.memdef]p3
10587 // - If a friend declaration in a non-local class first declares a
10588 // class or function, the friend class or function is a member
10589 // of the innermost enclosing namespace.
10590 // - The name of the friend is not found by simple name lookup
10591 // until a matching declaration is provided in that namespace
10592 // scope (either before or after the class declaration granting
10593 // friendship).
10594 // - If a friend function is called, its name may be found by the
10595 // name lookup that considers functions from namespaces and
10596 // classes associated with the types of the function arguments.
10597 // - When looking for a prior declaration of a class or a function
10598 // declared as a friend, scopes outside the innermost enclosing
10599 // namespace scope are not considered.
10600
John McCall337ec3d2010-10-12 23:13:28 +000010601 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010602 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10603 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010604 assert(Name);
10605
Douglas Gregor6ccab972010-12-16 01:14:37 +000010606 // Check for unexpanded parameter packs.
10607 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10608 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10609 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10610 return 0;
10611
John McCall67d1a672009-08-06 02:15:43 +000010612 // The context we found the declaration in, or in which we should
10613 // create the declaration.
10614 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010615 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010616 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010617 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010618
John McCall337ec3d2010-10-12 23:13:28 +000010619 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010620
John McCall337ec3d2010-10-12 23:13:28 +000010621 // There are four cases here.
10622 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010623 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010624 // there as appropriate.
10625 // Recover from invalid scope qualifiers as if they just weren't there.
10626 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010627 // C++0x [namespace.memdef]p3:
10628 // If the name in a friend declaration is neither qualified nor
10629 // a template-id and the declaration is a function or an
10630 // elaborated-type-specifier, the lookup to determine whether
10631 // the entity has been previously declared shall not consider
10632 // any scopes outside the innermost enclosing namespace.
10633 // C++0x [class.friend]p11:
10634 // If a friend declaration appears in a local class and the name
10635 // specified is an unqualified name, a prior declaration is
10636 // looked up without considering scopes that are outside the
10637 // innermost enclosing non-class scope. For a friend function
10638 // declaration, if there is no prior declaration, the program is
10639 // ill-formed.
10640 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010641 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010642
John McCall29ae6e52010-10-13 05:45:15 +000010643 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010644 DC = CurContext;
10645 while (true) {
10646 // Skip class contexts. If someone can cite chapter and verse
10647 // for this behavior, that would be nice --- it's what GCC and
10648 // EDG do, and it seems like a reasonable intent, but the spec
10649 // really only says that checks for unqualified existing
10650 // declarations should stop at the nearest enclosing namespace,
10651 // not that they should only consider the nearest enclosing
10652 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010653 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010654 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010655
John McCall68263142009-11-18 22:49:29 +000010656 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010657
10658 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010659 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010660 break;
John McCall29ae6e52010-10-13 05:45:15 +000010661
John McCall8a407372010-10-14 22:22:28 +000010662 if (isTemplateId) {
10663 if (isa<TranslationUnitDecl>(DC)) break;
10664 } else {
10665 if (DC->isFileContext()) break;
10666 }
John McCall67d1a672009-08-06 02:15:43 +000010667 DC = DC->getParent();
10668 }
10669
10670 // C++ [class.friend]p1: A friend of a class is a function or
10671 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010672 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010673 // Most C++ 98 compilers do seem to give an error here, so
10674 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010675 if (!Previous.empty() && DC->Equals(CurContext))
10676 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010677 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010678 diag::warn_cxx98_compat_friend_is_member :
10679 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010680
John McCall380aaa42010-10-13 06:22:15 +000010681 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010682
Douglas Gregor883af832011-10-10 01:11:59 +000010683 // C++ [class.friend]p6:
10684 // A function can be defined in a friend declaration of a class if and
10685 // only if the class is a non-local class (9.8), the function name is
10686 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010687 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010688 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10689 }
10690
John McCall337ec3d2010-10-12 23:13:28 +000010691 // - There's a non-dependent scope specifier, in which case we
10692 // compute it and do a previous lookup there for a function
10693 // or function template.
10694 } else if (!SS.getScopeRep()->isDependent()) {
10695 DC = computeDeclContext(SS);
10696 if (!DC) return 0;
10697
10698 if (RequireCompleteDeclContext(SS, DC)) return 0;
10699
10700 LookupQualifiedName(Previous, DC);
10701
10702 // Ignore things found implicitly in the wrong scope.
10703 // TODO: better diagnostics for this case. Suggesting the right
10704 // qualified scope would be nice...
10705 LookupResult::Filter F = Previous.makeFilter();
10706 while (F.hasNext()) {
10707 NamedDecl *D = F.next();
10708 if (!DC->InEnclosingNamespaceSetOf(
10709 D->getDeclContext()->getRedeclContext()))
10710 F.erase();
10711 }
10712 F.done();
10713
10714 if (Previous.empty()) {
10715 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010716 Diag(Loc, diag::err_qualified_friend_not_found)
10717 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010718 return 0;
10719 }
10720
10721 // C++ [class.friend]p1: A friend of a class is a function or
10722 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010723 if (DC->Equals(CurContext))
10724 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010725 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010726 diag::warn_cxx98_compat_friend_is_member :
10727 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010728
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010729 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010730 // C++ [class.friend]p6:
10731 // A function can be defined in a friend declaration of a class if and
10732 // only if the class is a non-local class (9.8), the function name is
10733 // unqualified, and the function has namespace scope.
10734 SemaDiagnosticBuilder DB
10735 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10736
10737 DB << SS.getScopeRep();
10738 if (DC->isFileContext())
10739 DB << FixItHint::CreateRemoval(SS.getRange());
10740 SS.clear();
10741 }
John McCall337ec3d2010-10-12 23:13:28 +000010742
10743 // - There's a scope specifier that does not match any template
10744 // parameter lists, in which case we use some arbitrary context,
10745 // create a method or method template, and wait for instantiation.
10746 // - There's a scope specifier that does match some template
10747 // parameter lists, which we don't handle right now.
10748 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010749 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010750 // C++ [class.friend]p6:
10751 // A function can be defined in a friend declaration of a class if and
10752 // only if the class is a non-local class (9.8), the function name is
10753 // unqualified, and the function has namespace scope.
10754 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10755 << SS.getScopeRep();
10756 }
10757
John McCall337ec3d2010-10-12 23:13:28 +000010758 DC = CurContext;
10759 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010760 }
Douglas Gregor883af832011-10-10 01:11:59 +000010761
John McCall29ae6e52010-10-13 05:45:15 +000010762 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010763 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010764 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10765 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10766 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010767 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010768 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10769 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010770 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010771 }
John McCall67d1a672009-08-06 02:15:43 +000010772 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010773
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010774 // FIXME: This is an egregious hack to cope with cases where the scope stack
10775 // does not contain the declaration context, i.e., in an out-of-line
10776 // definition of a class.
10777 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10778 if (!DCScope) {
10779 FakeDCScope.setEntity(DC);
10780 DCScope = &FakeDCScope;
10781 }
10782
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010783 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010784 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010785 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010786 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010787
Douglas Gregor182ddf02009-09-28 00:08:27 +000010788 assert(ND->getDeclContext() == DC);
10789 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010790
John McCallab88d972009-08-31 22:39:49 +000010791 // Add the function declaration to the appropriate lookup tables,
10792 // adjusting the redeclarations list as necessary. We don't
10793 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010794 //
John McCallab88d972009-08-31 22:39:49 +000010795 // Also update the scope-based lookup if the target context's
10796 // lookup context is in lexical scope.
10797 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010798 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010799 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010800 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010801 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010802 }
John McCall02cace72009-08-28 07:59:38 +000010803
10804 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010805 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010806 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010807 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010808 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010809
John McCall1f2e1a92012-08-10 03:15:35 +000010810 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010811 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010812 } else {
10813 if (DC->isRecord()) CheckFriendAccess(ND);
10814
John McCall6102ca12010-10-16 06:59:13 +000010815 FunctionDecl *FD;
10816 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10817 FD = FTD->getTemplatedDecl();
10818 else
10819 FD = cast<FunctionDecl>(ND);
10820
10821 // Mark templated-scope function declarations as unsupported.
10822 if (FD->getNumTemplateParameterLists())
10823 FrD->setUnsupportedFriend(true);
10824 }
John McCall337ec3d2010-10-12 23:13:28 +000010825
John McCalld226f652010-08-21 09:40:31 +000010826 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010827}
10828
John McCalld226f652010-08-21 09:40:31 +000010829void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10830 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010831
Sebastian Redl50de12f2009-03-24 22:27:57 +000010832 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10833 if (!Fn) {
10834 Diag(DelLoc, diag::err_deleted_non_function);
10835 return;
10836 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010837 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010838 // Don't consider the implicit declaration we generate for explicit
10839 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010840 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10841 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010842 Diag(DelLoc, diag::err_deleted_decl_not_first);
10843 Diag(Prev->getLocation(), diag::note_previous_declaration);
10844 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010845 // If the declaration wasn't the first, we delete the function anyway for
10846 // recovery.
10847 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010848 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010849}
Sebastian Redl13e88542009-04-27 21:33:24 +000010850
Sean Hunte4246a62011-05-12 06:15:49 +000010851void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10852 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10853
10854 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010855 if (MD->getParent()->isDependentType()) {
10856 MD->setDefaulted();
10857 MD->setExplicitlyDefaulted();
10858 return;
10859 }
10860
Sean Hunte4246a62011-05-12 06:15:49 +000010861 CXXSpecialMember Member = getSpecialMember(MD);
10862 if (Member == CXXInvalid) {
10863 Diag(DefaultLoc, diag::err_default_special_members);
10864 return;
10865 }
10866
10867 MD->setDefaulted();
10868 MD->setExplicitlyDefaulted();
10869
Sean Huntcd10dec2011-05-23 23:14:04 +000010870 // If this definition appears within the record, do the checking when
10871 // the record is complete.
10872 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010873 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010874 // Find the uninstantiated declaration that actually had the '= default'
10875 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010876 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010877
10878 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010879 return;
10880
Richard Smithb9d0b762012-07-27 04:22:15 +000010881 CheckExplicitlyDefaultedSpecialMember(MD);
10882
Sean Hunte4246a62011-05-12 06:15:49 +000010883 switch (Member) {
10884 case CXXDefaultConstructor: {
10885 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010886 if (!CD->isInvalidDecl())
10887 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10888 break;
10889 }
10890
10891 case CXXCopyConstructor: {
10892 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010893 if (!CD->isInvalidDecl())
10894 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010895 break;
10896 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010897
Sean Hunt2b188082011-05-14 05:23:28 +000010898 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010899 if (!MD->isInvalidDecl())
10900 DefineImplicitCopyAssignment(DefaultLoc, MD);
10901 break;
10902 }
10903
Sean Huntcb45a0f2011-05-12 22:46:25 +000010904 case CXXDestructor: {
10905 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010906 if (!DD->isInvalidDecl())
10907 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010908 break;
10909 }
10910
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010911 case CXXMoveConstructor: {
10912 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010913 if (!CD->isInvalidDecl())
10914 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010915 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010916 }
Sean Hunt82713172011-05-25 23:16:36 +000010917
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010918 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010919 if (!MD->isInvalidDecl())
10920 DefineImplicitMoveAssignment(DefaultLoc, MD);
10921 break;
10922 }
10923
10924 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010925 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010926 }
10927 } else {
10928 Diag(DefaultLoc, diag::err_default_special_members);
10929 }
10930}
10931
Sebastian Redl13e88542009-04-27 21:33:24 +000010932static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010933 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010934 Stmt *SubStmt = *CI;
10935 if (!SubStmt)
10936 continue;
10937 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010938 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010939 diag::err_return_in_constructor_handler);
10940 if (!isa<Expr>(SubStmt))
10941 SearchForReturnInStmt(Self, SubStmt);
10942 }
10943}
10944
10945void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10946 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10947 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10948 SearchForReturnInStmt(*this, Handler);
10949 }
10950}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010951
Mike Stump1eb44332009-09-09 15:08:12 +000010952bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010953 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010954 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10955 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010956
Chandler Carruth73857792010-02-15 11:53:20 +000010957 if (Context.hasSameType(NewTy, OldTy) ||
10958 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010959 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010960
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010961 // Check if the return types are covariant
10962 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010963
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010964 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010965 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10966 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010967 NewClassTy = NewPT->getPointeeType();
10968 OldClassTy = OldPT->getPointeeType();
10969 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010970 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10971 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10972 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10973 NewClassTy = NewRT->getPointeeType();
10974 OldClassTy = OldRT->getPointeeType();
10975 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010976 }
10977 }
Mike Stump1eb44332009-09-09 15:08:12 +000010978
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010979 // The return types aren't either both pointers or references to a class type.
10980 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010981 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010982 diag::err_different_return_type_for_overriding_virtual_function)
10983 << New->getDeclName() << NewTy << OldTy;
10984 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010985
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010986 return true;
10987 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010988
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010989 // C++ [class.virtual]p6:
10990 // If the return type of D::f differs from the return type of B::f, the
10991 // class type in the return type of D::f shall be complete at the point of
10992 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010993 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10994 if (!RT->isBeingDefined() &&
10995 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010996 diag::err_covariant_return_incomplete,
10997 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010998 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010999 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011000
Douglas Gregora4923eb2009-11-16 21:35:15 +000011001 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011002 // Check if the new class derives from the old class.
11003 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11004 Diag(New->getLocation(),
11005 diag::err_covariant_return_not_derived)
11006 << New->getDeclName() << NewTy << OldTy;
11007 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11008 return true;
11009 }
Mike Stump1eb44332009-09-09 15:08:12 +000011010
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011011 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011012 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011013 diag::err_covariant_return_inaccessible_base,
11014 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11015 // FIXME: Should this point to the return type?
11016 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011017 // FIXME: this note won't trigger for delayed access control
11018 // diagnostics, and it's impossible to get an undelayed error
11019 // here from access control during the original parse because
11020 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011021 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11022 return true;
11023 }
11024 }
Mike Stump1eb44332009-09-09 15:08:12 +000011025
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011026 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011027 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011028 Diag(New->getLocation(),
11029 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011030 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011031 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11032 return true;
11033 };
Mike Stump1eb44332009-09-09 15:08:12 +000011034
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011035
11036 // The new class type must have the same or less qualifiers as the old type.
11037 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11038 Diag(New->getLocation(),
11039 diag::err_covariant_return_type_class_type_more_qualified)
11040 << New->getDeclName() << NewTy << OldTy;
11041 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11042 return true;
11043 };
Mike Stump1eb44332009-09-09 15:08:12 +000011044
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011045 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011046}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011047
Douglas Gregor4ba31362009-12-01 17:24:26 +000011048/// \brief Mark the given method pure.
11049///
11050/// \param Method the method to be marked pure.
11051///
11052/// \param InitRange the source range that covers the "0" initializer.
11053bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011054 SourceLocation EndLoc = InitRange.getEnd();
11055 if (EndLoc.isValid())
11056 Method->setRangeEnd(EndLoc);
11057
Douglas Gregor4ba31362009-12-01 17:24:26 +000011058 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11059 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011060 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011061 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011062
11063 if (!Method->isInvalidDecl())
11064 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11065 << Method->getDeclName() << InitRange;
11066 return true;
11067}
11068
Douglas Gregor552e2992012-02-21 02:22:07 +000011069/// \brief Determine whether the given declaration is a static data member.
11070static bool isStaticDataMember(Decl *D) {
11071 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11072 if (!Var)
11073 return false;
11074
11075 return Var->isStaticDataMember();
11076}
John McCall731ad842009-12-19 09:28:58 +000011077/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11078/// an initializer for the out-of-line declaration 'Dcl'. The scope
11079/// is a fresh scope pushed for just this purpose.
11080///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011081/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11082/// static data member of class X, names should be looked up in the scope of
11083/// class X.
John McCalld226f652010-08-21 09:40:31 +000011084void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011085 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011086 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011087
John McCall731ad842009-12-19 09:28:58 +000011088 // We should only get called for declarations with scope specifiers, like:
11089 // int foo::bar;
11090 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011091 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011092
11093 // If we are parsing the initializer for a static data member, push a
11094 // new expression evaluation context that is associated with this static
11095 // data member.
11096 if (isStaticDataMember(D))
11097 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011098}
11099
11100/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011101/// initializer for the out-of-line declaration 'D'.
11102void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011103 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011104 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011105
Douglas Gregor552e2992012-02-21 02:22:07 +000011106 if (isStaticDataMember(D))
11107 PopExpressionEvaluationContext();
11108
John McCall731ad842009-12-19 09:28:58 +000011109 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011110 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011111}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011112
11113/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11114/// C++ if/switch/while/for statement.
11115/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011116DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011117 // C++ 6.4p2:
11118 // The declarator shall not specify a function or an array.
11119 // The type-specifier-seq shall not contain typedef and shall not declare a
11120 // new class or enumeration.
11121 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11122 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011123
11124 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011125 if (!Dcl)
11126 return true;
11127
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011128 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11129 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011130 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011131 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011132 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011133
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011134 return Dcl;
11135}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011136
Douglas Gregordfe65432011-07-28 19:11:31 +000011137void Sema::LoadExternalVTableUses() {
11138 if (!ExternalSource)
11139 return;
11140
11141 SmallVector<ExternalVTableUse, 4> VTables;
11142 ExternalSource->ReadUsedVTables(VTables);
11143 SmallVector<VTableUse, 4> NewUses;
11144 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11145 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11146 = VTablesUsed.find(VTables[I].Record);
11147 // Even if a definition wasn't required before, it may be required now.
11148 if (Pos != VTablesUsed.end()) {
11149 if (!Pos->second && VTables[I].DefinitionRequired)
11150 Pos->second = true;
11151 continue;
11152 }
11153
11154 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11155 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11156 }
11157
11158 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11159}
11160
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011161void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11162 bool DefinitionRequired) {
11163 // Ignore any vtable uses in unevaluated operands or for classes that do
11164 // not have a vtable.
11165 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11166 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011167 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011168 return;
11169
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011170 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011171 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011172 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11173 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11174 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11175 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011176 // If we already had an entry, check to see if we are promoting this vtable
11177 // to required a definition. If so, we need to reappend to the VTableUses
11178 // list, since we may have already processed the first entry.
11179 if (DefinitionRequired && !Pos.first->second) {
11180 Pos.first->second = true;
11181 } else {
11182 // Otherwise, we can early exit.
11183 return;
11184 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011185 }
11186
11187 // Local classes need to have their virtual members marked
11188 // immediately. For all other classes, we mark their virtual members
11189 // at the end of the translation unit.
11190 if (Class->isLocalClass())
11191 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011192 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011193 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011194}
11195
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011196bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011197 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011198 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011199 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011200
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011201 // Note: The VTableUses vector could grow as a result of marking
11202 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011203 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011204 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011205 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011206 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011207 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011208 if (!Class)
11209 continue;
11210
11211 SourceLocation Loc = VTableUses[I].second;
11212
Richard Smithb9d0b762012-07-27 04:22:15 +000011213 bool DefineVTable = true;
11214
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011215 // If this class has a key function, but that key function is
11216 // defined in another translation unit, we don't need to emit the
11217 // vtable even though we're using it.
11218 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011219 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011220 switch (KeyFunction->getTemplateSpecializationKind()) {
11221 case TSK_Undeclared:
11222 case TSK_ExplicitSpecialization:
11223 case TSK_ExplicitInstantiationDeclaration:
11224 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011225 DefineVTable = false;
11226 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011227
11228 case TSK_ExplicitInstantiationDefinition:
11229 case TSK_ImplicitInstantiation:
11230 // We will be instantiating the key function.
11231 break;
11232 }
11233 } else if (!KeyFunction) {
11234 // If we have a class with no key function that is the subject
11235 // of an explicit instantiation declaration, suppress the
11236 // vtable; it will live with the explicit instantiation
11237 // definition.
11238 bool IsExplicitInstantiationDeclaration
11239 = Class->getTemplateSpecializationKind()
11240 == TSK_ExplicitInstantiationDeclaration;
11241 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11242 REnd = Class->redecls_end();
11243 R != REnd; ++R) {
11244 TemplateSpecializationKind TSK
11245 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11246 if (TSK == TSK_ExplicitInstantiationDeclaration)
11247 IsExplicitInstantiationDeclaration = true;
11248 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11249 IsExplicitInstantiationDeclaration = false;
11250 break;
11251 }
11252 }
11253
11254 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011255 DefineVTable = false;
11256 }
11257
11258 // The exception specifications for all virtual members may be needed even
11259 // if we are not providing an authoritative form of the vtable in this TU.
11260 // We may choose to emit it available_externally anyway.
11261 if (!DefineVTable) {
11262 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11263 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011264 }
11265
11266 // Mark all of the virtual members of this class as referenced, so
11267 // that we can build a vtable. Then, tell the AST consumer that a
11268 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011269 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011270 MarkVirtualMembersReferenced(Loc, Class);
11271 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11272 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11273
11274 // Optionally warn if we're emitting a weak vtable.
11275 if (Class->getLinkage() == ExternalLinkage &&
11276 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011277 const FunctionDecl *KeyFunctionDef = 0;
11278 if (!KeyFunction ||
11279 (KeyFunction->hasBody(KeyFunctionDef) &&
11280 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011281 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11282 TSK_ExplicitInstantiationDefinition
11283 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11284 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011285 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011286 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011287 VTableUses.clear();
11288
Douglas Gregor78844032011-04-22 22:25:37 +000011289 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011290}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011291
Richard Smithb9d0b762012-07-27 04:22:15 +000011292void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11293 const CXXRecordDecl *RD) {
11294 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11295 E = RD->method_end(); I != E; ++I)
11296 if ((*I)->isVirtual() && !(*I)->isPure())
11297 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11298}
11299
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011300void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11301 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011302 // Mark all functions which will appear in RD's vtable as used.
11303 CXXFinalOverriderMap FinalOverriders;
11304 RD->getFinalOverriders(FinalOverriders);
11305 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11306 E = FinalOverriders.end();
11307 I != E; ++I) {
11308 for (OverridingMethods::const_iterator OI = I->second.begin(),
11309 OE = I->second.end();
11310 OI != OE; ++OI) {
11311 assert(OI->second.size() > 0 && "no final overrider");
11312 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011313
Richard Smithff817f72012-07-07 06:59:51 +000011314 // C++ [basic.def.odr]p2:
11315 // [...] A virtual member function is used if it is not pure. [...]
11316 if (!Overrider->isPure())
11317 MarkFunctionReferenced(Loc, Overrider);
11318 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011319 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011320
11321 // Only classes that have virtual bases need a VTT.
11322 if (RD->getNumVBases() == 0)
11323 return;
11324
11325 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11326 e = RD->bases_end(); i != e; ++i) {
11327 const CXXRecordDecl *Base =
11328 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011329 if (Base->getNumVBases() == 0)
11330 continue;
11331 MarkVirtualMembersReferenced(Loc, Base);
11332 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011333}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011334
11335/// SetIvarInitializers - This routine builds initialization ASTs for the
11336/// Objective-C implementation whose ivars need be initialized.
11337void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011338 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011339 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011340 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011341 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011342 CollectIvarsToConstructOrDestruct(OID, ivars);
11343 if (ivars.empty())
11344 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011345 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011346 for (unsigned i = 0; i < ivars.size(); i++) {
11347 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011348 if (Field->isInvalidDecl())
11349 continue;
11350
Sean Huntcbb67482011-01-08 20:30:50 +000011351 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011352 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11353 InitializationKind InitKind =
11354 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11355
11356 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011357 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011358 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011359 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011360 // Note, MemberInit could actually come back empty if no initialization
11361 // is required (e.g., because it would call a trivial default constructor)
11362 if (!MemberInit.get() || MemberInit.isInvalid())
11363 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011364
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011365 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011366 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11367 SourceLocation(),
11368 MemberInit.takeAs<Expr>(),
11369 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011370 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011371
11372 // Be sure that the destructor is accessible and is marked as referenced.
11373 if (const RecordType *RecordTy
11374 = Context.getBaseElementType(Field->getType())
11375 ->getAs<RecordType>()) {
11376 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011377 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011378 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011379 CheckDestructorAccess(Field->getLocation(), Destructor,
11380 PDiag(diag::err_access_dtor_ivar)
11381 << Context.getBaseElementType(Field->getType()));
11382 }
11383 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011384 }
11385 ObjCImplementation->setIvarInitializers(Context,
11386 AllToInit.data(), AllToInit.size());
11387 }
11388}
Sean Huntfe57eef2011-05-04 05:57:24 +000011389
Sean Huntebcbe1d2011-05-04 23:29:54 +000011390static
11391void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11392 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11393 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11394 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11395 Sema &S) {
11396 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11397 CE = Current.end();
11398 if (Ctor->isInvalidDecl())
11399 return;
11400
Richard Smitha8eaf002012-08-23 06:16:52 +000011401 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11402
11403 // Target may not be determinable yet, for instance if this is a dependent
11404 // call in an uninstantiated template.
11405 if (Target) {
11406 const FunctionDecl *FNTarget = 0;
11407 (void)Target->hasBody(FNTarget);
11408 Target = const_cast<CXXConstructorDecl*>(
11409 cast_or_null<CXXConstructorDecl>(FNTarget));
11410 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011411
11412 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11413 // Avoid dereferencing a null pointer here.
11414 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11415
11416 if (!Current.insert(Canonical))
11417 return;
11418
11419 // We know that beyond here, we aren't chaining into a cycle.
11420 if (!Target || !Target->isDelegatingConstructor() ||
11421 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11422 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11423 Valid.insert(*CI);
11424 Current.clear();
11425 // We've hit a cycle.
11426 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11427 Current.count(TCanonical)) {
11428 // If we haven't diagnosed this cycle yet, do so now.
11429 if (!Invalid.count(TCanonical)) {
11430 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011431 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011432 << Ctor;
11433
Richard Smitha8eaf002012-08-23 06:16:52 +000011434 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011435 if (TCanonical != Canonical)
11436 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11437
11438 CXXConstructorDecl *C = Target;
11439 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011440 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011441 (void)C->getTargetConstructor()->hasBody(FNTarget);
11442 assert(FNTarget && "Ctor cycle through bodiless function");
11443
Richard Smitha8eaf002012-08-23 06:16:52 +000011444 C = const_cast<CXXConstructorDecl*>(
11445 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011446 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11447 }
11448 }
11449
11450 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11451 Invalid.insert(*CI);
11452 Current.clear();
11453 } else {
11454 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11455 }
11456}
11457
11458
Sean Huntfe57eef2011-05-04 05:57:24 +000011459void Sema::CheckDelegatingCtorCycles() {
11460 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11461
Sean Huntebcbe1d2011-05-04 23:29:54 +000011462 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11463 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011464
Douglas Gregor0129b562011-07-27 21:57:17 +000011465 for (DelegatingCtorDeclsType::iterator
11466 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011467 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011468 I != E; ++I)
11469 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011470
11471 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11472 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011473}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011474
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011475namespace {
11476 /// \brief AST visitor that finds references to the 'this' expression.
11477 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11478 Sema &S;
11479
11480 public:
11481 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11482
11483 bool VisitCXXThisExpr(CXXThisExpr *E) {
11484 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11485 << E->isImplicit();
11486 return false;
11487 }
11488 };
11489}
11490
11491bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11492 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11493 if (!TSInfo)
11494 return false;
11495
11496 TypeLoc TL = TSInfo->getTypeLoc();
11497 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11498 if (!ProtoTL)
11499 return false;
11500
11501 // C++11 [expr.prim.general]p3:
11502 // [The expression this] shall not appear before the optional
11503 // cv-qualifier-seq and it shall not appear within the declaration of a
11504 // static member function (although its type and value category are defined
11505 // within a static member function as they are within a non-static member
11506 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011507 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011508 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11509 FindCXXThisExpr Finder(*this);
11510
11511 // If the return type came after the cv-qualifier-seq, check it now.
11512 if (Proto->hasTrailingReturn() &&
11513 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11514 return true;
11515
11516 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011517 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11518 return true;
11519
11520 return checkThisInStaticMemberFunctionAttributes(Method);
11521}
11522
11523bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11524 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11525 if (!TSInfo)
11526 return false;
11527
11528 TypeLoc TL = TSInfo->getTypeLoc();
11529 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11530 if (!ProtoTL)
11531 return false;
11532
11533 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11534 FindCXXThisExpr Finder(*this);
11535
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011536 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011537 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011538 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011539 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011540 case EST_DynamicNone:
11541 case EST_MSAny:
11542 case EST_None:
11543 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011544
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011545 case EST_ComputedNoexcept:
11546 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11547 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011548
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011549 case EST_Dynamic:
11550 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011551 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011552 E != EEnd; ++E) {
11553 if (!Finder.TraverseType(*E))
11554 return true;
11555 }
11556 break;
11557 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011558
11559 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011560}
11561
11562bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11563 FindCXXThisExpr Finder(*this);
11564
11565 // Check attributes.
11566 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11567 A != AEnd; ++A) {
11568 // FIXME: This should be emitted by tblgen.
11569 Expr *Arg = 0;
11570 ArrayRef<Expr *> Args;
11571 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11572 Arg = G->getArg();
11573 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11574 Arg = G->getArg();
11575 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11576 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11577 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11578 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11579 else if (ExclusiveLockFunctionAttr *ELF
11580 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11581 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11582 else if (SharedLockFunctionAttr *SLF
11583 = dyn_cast<SharedLockFunctionAttr>(*A))
11584 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11585 else if (ExclusiveTrylockFunctionAttr *ETLF
11586 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11587 Arg = ETLF->getSuccessValue();
11588 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11589 } else if (SharedTrylockFunctionAttr *STLF
11590 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11591 Arg = STLF->getSuccessValue();
11592 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11593 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11594 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11595 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11596 Arg = LR->getArg();
11597 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11598 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11599 else if (ExclusiveLocksRequiredAttr *ELR
11600 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11601 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11602 else if (SharedLocksRequiredAttr *SLR
11603 = dyn_cast<SharedLocksRequiredAttr>(*A))
11604 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11605
11606 if (Arg && !Finder.TraverseStmt(Arg))
11607 return true;
11608
11609 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11610 if (!Finder.TraverseStmt(Args[I]))
11611 return true;
11612 }
11613 }
11614
11615 return false;
11616}
11617
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011618void
11619Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11620 ArrayRef<ParsedType> DynamicExceptions,
11621 ArrayRef<SourceRange> DynamicExceptionRanges,
11622 Expr *NoexceptExpr,
11623 llvm::SmallVectorImpl<QualType> &Exceptions,
11624 FunctionProtoType::ExtProtoInfo &EPI) {
11625 Exceptions.clear();
11626 EPI.ExceptionSpecType = EST;
11627 if (EST == EST_Dynamic) {
11628 Exceptions.reserve(DynamicExceptions.size());
11629 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11630 // FIXME: Preserve type source info.
11631 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11632
11633 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11634 collectUnexpandedParameterPacks(ET, Unexpanded);
11635 if (!Unexpanded.empty()) {
11636 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11637 UPPC_ExceptionType,
11638 Unexpanded);
11639 continue;
11640 }
11641
11642 // Check that the type is valid for an exception spec, and
11643 // drop it if not.
11644 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11645 Exceptions.push_back(ET);
11646 }
11647 EPI.NumExceptions = Exceptions.size();
11648 EPI.Exceptions = Exceptions.data();
11649 return;
11650 }
11651
11652 if (EST == EST_ComputedNoexcept) {
11653 // If an error occurred, there's no expression here.
11654 if (NoexceptExpr) {
11655 assert((NoexceptExpr->isTypeDependent() ||
11656 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11657 Context.BoolTy) &&
11658 "Parser should have made sure that the expression is boolean");
11659 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11660 EPI.ExceptionSpecType = EST_BasicNoexcept;
11661 return;
11662 }
11663
11664 if (!NoexceptExpr->isValueDependent())
11665 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011666 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011667 /*AllowFold*/ false).take();
11668 EPI.NoexceptExpr = NoexceptExpr;
11669 }
11670 return;
11671 }
11672}
11673
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011674/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11675Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11676 // Implicitly declared functions (e.g. copy constructors) are
11677 // __host__ __device__
11678 if (D->isImplicit())
11679 return CFT_HostDevice;
11680
11681 if (D->hasAttr<CUDAGlobalAttr>())
11682 return CFT_Global;
11683
11684 if (D->hasAttr<CUDADeviceAttr>()) {
11685 if (D->hasAttr<CUDAHostAttr>())
11686 return CFT_HostDevice;
11687 else
11688 return CFT_Device;
11689 }
11690
11691 return CFT_Host;
11692}
11693
11694bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11695 CUDAFunctionTarget CalleeTarget) {
11696 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11697 // Callable from the device only."
11698 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11699 return true;
11700
11701 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11702 // Callable from the host only."
11703 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11704 // Callable from the host only."
11705 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11706 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11707 return true;
11708
11709 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11710 return true;
11711
11712 return false;
11713}