blob: 8198856547c69835a5522706642434432a830b35 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000068 };
Chris Lattner8123a952008-04-10 02:22:51 +000069
Chris Lattner9e979552008-04-12 23:52:44 +000070 /// VisitExpr - Visit all of the children of this expression.
71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000073 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000074 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000075 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000076 }
77
Chris Lattner9e979552008-04-12 23:52:44 +000078 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000082 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000083 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000092 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000093 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000094 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000095 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000096 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
98 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000099 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000100 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104
Douglas Gregor3996f232008-11-04 13:41:56 +0000105 return false;
106 }
Chris Lattner9e979552008-04-12 23:52:44 +0000107
Douglas Gregor796da182008-11-04 14:32:21 +0000108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
112 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000113 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000116 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000117
118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
123 return false;
124
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
127 }
Chris Lattner8123a952008-04-10 02:22:51 +0000128}
129
Richard Smithe6975e92012-04-17 00:58:00 +0000130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000134 return;
135
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139 if (!Proto)
140 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000141
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000145 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000146 ClearExceptions();
147 ComputedEST = EST;
148 return;
149 }
150
Richard Smith7a614d82011-06-11 17:19:42 +0000151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
153
Sean Hunt001cad92011-05-10 00:49:42 +0000154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
156 return;
157
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
160 return;
161
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
167 return;
168 }
169
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
179
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
182 ClearExceptions();
183 ComputedEST = EST_None;
184 }
185 // noexcept(true) won't change anything either.
186 return;
187 }
188
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
196 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000198 Exceptions.push_back(*E);
199}
200
Richard Smith7a614d82011-06-11 17:19:42 +0000201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000202 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000203 return;
204
205 // FIXME:
206 //
207 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
213 //
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
217 //
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
220 //
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
225
Richard Smithe6975e92012-04-17 00:58:00 +0000226 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000227 ComputedEST = EST_None;
228}
229
Anders Carlssoned961f92009-08-25 02:29:20 +0000230bool
John McCall9ae2f072010-08-23 23:25:46 +0000231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
236 return true;
237 }
238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000251 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000252 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000253 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000254
Richard Smith6c3af3d2013-01-17 01:17:56 +0000255 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Craig Topper1a6eac82012-09-21 04:33:26 +0000377/// MergeCXXFunctionDecl - Merge two declarations of the same C++
378/// function, once we already know that they have the same
379/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
521 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000522 }
523 }
524
Richard Smithb8abff62012-11-28 03:45:24 +0000525 // DR1344: If a default argument is added outside a class definition and that
526 // default argument makes the function a special member function, the program
527 // is ill-formed. This can only happen for constructors.
528 if (isa<CXXConstructorDecl>(New) &&
529 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
530 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
531 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
532 if (NewSM != OldSM) {
533 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
534 assert(NewParam->hasDefaultArg());
535 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
536 << NewParam->getDefaultArgRange() << NewSM;
537 Diag(Old->getLocation(), diag::note_previous_declaration);
538 }
539 }
540
Richard Smithff234882012-02-20 23:28:05 +0000541 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000542 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000543 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000544 if (New->isConstexpr() != Old->isConstexpr()) {
545 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
546 << New << New->isConstexpr();
547 Diag(Old->getLocation(), diag::note_previous_declaration);
548 Invalid = true;
549 }
550
Douglas Gregore13ad832010-02-12 07:32:17 +0000551 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000552 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000553
Douglas Gregorcda9c672009-02-16 17:45:42 +0000554 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000555}
556
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557/// \brief Merge the exception specifications of two variable declarations.
558///
559/// This is called when there's a redeclaration of a VarDecl. The function
560/// checks if the redeclaration might have an exception specification and
561/// validates compatibility and merges the specs if necessary.
562void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
563 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000564 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000565 return;
566
567 assert(Context.hasSameType(New->getType(), Old->getType()) &&
568 "Should only be called if types are otherwise the same.");
569
570 QualType NewType = New->getType();
571 QualType OldType = Old->getType();
572
573 // We're only interested in pointers and references to functions, as well
574 // as pointers to member functions.
575 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
576 NewType = R->getPointeeType();
577 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
578 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
579 NewType = P->getPointeeType();
580 OldType = OldType->getAs<PointerType>()->getPointeeType();
581 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
582 NewType = M->getPointeeType();
583 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
584 }
585
586 if (!NewType->isFunctionProtoType())
587 return;
588
589 // There's lots of special cases for functions. For function pointers, system
590 // libraries are hopefully not as broken so that we don't need these
591 // workarounds.
592 if (CheckEquivalentExceptionSpec(
593 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
594 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
595 New->setInvalidDecl();
596 }
597}
598
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599/// CheckCXXDefaultArguments - Verify that the default arguments for a
600/// function declaration are well-formed according to C++
601/// [dcl.fct.default].
602void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
603 unsigned NumParams = FD->getNumParams();
604 unsigned p;
605
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
607 isa<CXXMethodDecl>(FD) &&
608 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610 // Find first parameter with a default argument
611 for (p = 0; p < NumParams; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000613 if (Param->hasDefaultArg()) {
614 // C++11 [expr.prim.lambda]p5:
615 // [...] Default arguments (8.3.6) shall not be specified in the
616 // parameter-declaration-clause of a lambda-declarator.
617 //
618 // FIXME: Core issue 974 strikes this sentence, we only provide an
619 // extension warning.
620 if (IsLambda)
621 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
622 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000623 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000625 }
626
627 // C++ [dcl.fct.default]p4:
628 // In a given function declaration, all parameters
629 // subsequent to a parameter with a default argument shall
630 // have default arguments supplied in this or previous
631 // declarations. A default argument shall not be redefined
632 // by a later declaration (not even to the same value).
633 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000634 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000636 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000637 if (Param->isInvalidDecl())
638 /* We already complained about this parameter. */;
639 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000640 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000641 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000642 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000643 else
Mike Stump1eb44332009-09-09 15:08:12 +0000644 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000645 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner3d1cee32008-04-08 05:04:30 +0000647 LastMissingDefaultArg = p;
648 }
649 }
650
651 if (LastMissingDefaultArg > 0) {
652 // Some default arguments were missing. Clear out all of the
653 // default arguments up to (and including) the last missing
654 // default argument, so that we leave the function parameters
655 // in a semantically valid state.
656 for (p = 0; p <= LastMissingDefaultArg; ++p) {
657 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000658 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 Param->setDefaultArg(0);
660 }
661 }
662 }
663}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000664
Richard Smith9f569cc2011-10-01 02:31:28 +0000665// CheckConstexprParameterTypes - Check whether a function's parameter types
666// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000667// diagnostic and return false.
668static bool CheckConstexprParameterTypes(Sema &SemaRef,
669 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000670 unsigned ArgIndex = 0;
671 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
672 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
673 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
674 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
675 SourceLocation ParamLoc = PD->getLocation();
676 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000677 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000678 diag::err_constexpr_non_literal_param,
679 ArgIndex+1, PD->getSourceRange(),
680 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000682 }
Joao Matos17d35c32012-08-31 22:18:20 +0000683 return true;
684}
685
686/// \brief Get diagnostic %select index for tag kind for
687/// record diagnostic message.
688/// WARNING: Indexes apply to particular diagnostics only!
689///
690/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000691static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000692 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000693 case TTK_Struct: return 0;
694 case TTK_Interface: return 1;
695 case TTK_Class: return 2;
696 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000697 }
Joao Matos17d35c32012-08-31 22:18:20 +0000698}
699
700// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
701// the requirements of a constexpr function definition or a constexpr
702// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000703// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000704//
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
706bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
708 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000709 // C++11 [dcl.constexpr]p4:
710 // The definition of a constexpr constructor shall satisfy the following
711 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000713 const CXXRecordDecl *RD = MD->getParent();
714 if (RD->getNumVBases()) {
715 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
716 << isa<CXXConstructorDecl>(NewFD)
717 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
718 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
719 E = RD->vbases_end(); I != E; ++I)
720 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000721 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
Richard Smith35340502012-01-13 04:54:00 +0000724 }
725
726 if (!isa<CXXConstructorDecl>(NewFD)) {
727 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // The definition of a constexpr function shall satisfy the following
729 // constraints:
730 // - it shall not be virtual;
731 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
732 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000734
Richard Smith86c3ae42012-02-13 03:54:03 +0000735 // If it's not obvious why this function is virtual, find an overridden
736 // function which uses the 'virtual' keyword.
737 const CXXMethodDecl *WrittenVirtual = Method;
738 while (!WrittenVirtual->isVirtualAsWritten())
739 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
740 if (WrittenVirtual != Method)
741 Diag(WrittenVirtual->getLocation(),
742 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000743 return false;
744 }
745
746 // - its return type shall be a literal type;
747 QualType RT = NewFD->getResultType();
748 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000750 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 }
753
Richard Smith35340502012-01-13 04:54:00 +0000754 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000755 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000756 return false;
757
Richard Smith9f569cc2011-10-01 02:31:28 +0000758 return true;
759}
760
761/// Check the given declaration statement is legal within a constexpr function
762/// body. C++0x [dcl.constexpr]p3,p4.
763///
764/// \return true if the body is OK, false if we have diagnosed a problem.
765static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
766 DeclStmt *DS) {
767 // C++0x [dcl.constexpr]p3 and p4:
768 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
769 // contain only
770 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
771 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
772 switch ((*DclIt)->getKind()) {
773 case Decl::StaticAssert:
774 case Decl::Using:
775 case Decl::UsingShadow:
776 case Decl::UsingDirective:
777 case Decl::UnresolvedUsingTypename:
778 // - static_assert-declarations
779 // - using-declarations,
780 // - using-directives,
781 continue;
782
783 case Decl::Typedef:
784 case Decl::TypeAlias: {
785 // - typedef declarations and alias-declarations that do not define
786 // classes or enumerations,
787 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
788 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
789 // Don't allow variably-modified types in constexpr functions.
790 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
791 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
792 << TL.getSourceRange() << TL.getType()
793 << isa<CXXConstructorDecl>(Dcl);
794 return false;
795 }
796 continue;
797 }
798
799 case Decl::Enum:
800 case Decl::CXXRecord:
801 // As an extension, we allow the declaration (but not the definition) of
802 // classes and enumerations in all declarations, not just in typedef and
803 // alias declarations.
804 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
805 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
806 << isa<CXXConstructorDecl>(Dcl);
807 return false;
808 }
809 continue;
810
811 case Decl::Var:
812 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
813 << isa<CXXConstructorDecl>(Dcl);
814 return false;
815
816 default:
817 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
818 << isa<CXXConstructorDecl>(Dcl);
819 return false;
820 }
821 }
822
823 return true;
824}
825
826/// Check that the given field is initialized within a constexpr constructor.
827///
828/// \param Dcl The constexpr constructor being checked.
829/// \param Field The field being checked. This may be a member of an anonymous
830/// struct or union nested within the class being checked.
831/// \param Inits All declarations, including anonymous struct/union members and
832/// indirect members, for which any initialization was provided.
833/// \param Diagnosed Set to true if an error is produced.
834static void CheckConstexprCtorInitializer(Sema &SemaRef,
835 const FunctionDecl *Dcl,
836 FieldDecl *Field,
837 llvm::SmallSet<Decl*, 16> &Inits,
838 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000839 if (Field->isUnnamedBitfield())
840 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000841
842 if (Field->isAnonymousStructOrUnion() &&
843 Field->getType()->getAsCXXRecordDecl()->isEmpty())
844 return;
845
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (!Inits.count(Field)) {
847 if (!Diagnosed) {
848 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
849 Diagnosed = true;
850 }
851 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
852 } else if (Field->isAnonymousStructOrUnion()) {
853 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
854 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
855 I != E; ++I)
856 // If an anonymous union contains an anonymous struct of which any member
857 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000858 if (!RD->isUnion() || Inits.count(*I))
859 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000860 }
861}
862
863/// Check the body for the given constexpr function declaration only contains
864/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
865///
866/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000867bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000868 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000869 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000870 // The definition of a constexpr function shall satisfy the following
871 // constraints: [...]
872 // - its function-body shall be = delete, = default, or a
873 // compound-statement
874 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000875 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 // In the definition of a constexpr constructor, [...]
877 // - its function-body shall not be a function-try-block;
878 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882
883 // - its function-body shall be [...] a compound-statement that contains only
884 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
885
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000886 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
888 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
889 switch ((*BodyIt)->getStmtClass()) {
890 case Stmt::NullStmtClass:
891 // - null statements,
892 continue;
893
894 case Stmt::DeclStmtClass:
895 // - static_assert-declarations
896 // - using-declarations,
897 // - using-directives,
898 // - typedef declarations and alias-declarations that do not define
899 // classes or enumerations,
900 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
901 return false;
902 continue;
903
904 case Stmt::ReturnStmtClass:
905 // - and exactly one return statement;
906 if (isa<CXXConstructorDecl>(Dcl))
907 break;
908
909 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 continue;
911
912 default:
913 break;
914 }
915
916 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
917 << isa<CXXConstructorDecl>(Dcl);
918 return false;
919 }
920
921 if (const CXXConstructorDecl *Constructor
922 = dyn_cast<CXXConstructorDecl>(Dcl)) {
923 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000924 // DR1359:
925 // - every non-variant non-static data member and base class sub-object
926 // shall be initialized;
927 // - if the class is a non-empty union, or for each non-empty anonymous
928 // union member of a non-union class, exactly one non-static data member
929 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000930 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000931 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000932 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
933 return false;
934 }
Richard Smith6e433752011-10-10 16:38:04 +0000935 } else if (!Constructor->isDependentContext() &&
936 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000937 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
938
939 // Skip detailed checking if we have enough initializers, and we would
940 // allow at most one initializer per member.
941 bool AnyAnonStructUnionMembers = false;
942 unsigned Fields = 0;
943 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
944 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000945 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 AnyAnonStructUnionMembers = true;
947 break;
948 }
949 }
950 if (AnyAnonStructUnionMembers ||
951 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
952 // Check initialization of non-static data members. Base classes are
953 // always initialized so do not need to be checked. Dependent bases
954 // might not have initializers in the member initializer list.
955 llvm::SmallSet<Decl*, 16> Inits;
956 for (CXXConstructorDecl::init_const_iterator
957 I = Constructor->init_begin(), E = Constructor->init_end();
958 I != E; ++I) {
959 if (FieldDecl *FD = (*I)->getMember())
960 Inits.insert(FD);
961 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
962 Inits.insert(ID->chain_begin(), ID->chain_end());
963 }
964
965 bool Diagnosed = false;
966 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
967 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000968 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000969 if (Diagnosed)
970 return false;
971 }
972 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000973 } else {
974 if (ReturnStmts.empty()) {
975 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
976 return false;
977 }
978 if (ReturnStmts.size() > 1) {
979 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
980 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
981 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
982 return false;
983 }
984 }
985
Richard Smith5ba73e12012-02-04 00:33:54 +0000986 // C++11 [dcl.constexpr]p5:
987 // if no function argument values exist such that the function invocation
988 // substitution would produce a constant expression, the program is
989 // ill-formed; no diagnostic required.
990 // C++11 [dcl.constexpr]p3:
991 // - every constructor call and implicit conversion used in initializing the
992 // return value shall be one of those allowed in a constant expression.
993 // C++11 [dcl.constexpr]p4:
994 // - every constructor involved in initializing non-static data members and
995 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000996 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000997 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +0000998 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +0000999 << isa<CXXConstructorDecl>(Dcl);
1000 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1001 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001002 // Don't return false here: we allow this for compatibility in
1003 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001004 }
1005
Richard Smith9f569cc2011-10-01 02:31:28 +00001006 return true;
1007}
1008
Douglas Gregorb48fe382008-10-31 09:07:45 +00001009/// isCurrentClassName - Determine whether the identifier II is the
1010/// name of the class type currently being defined. In the case of
1011/// nested classes, this will only return true if II is the name of
1012/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001013bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1014 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001015 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001016
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001017 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001018 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001019 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001020 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1021 } else
1022 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1023
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001024 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001025 return &II == CurDecl->getIdentifier();
1026 else
1027 return false;
1028}
1029
Douglas Gregor229d47a2012-11-10 07:24:09 +00001030/// \brief Determine whether the given class is a base class of the given
1031/// class, including looking at dependent bases.
1032static bool findCircularInheritance(const CXXRecordDecl *Class,
1033 const CXXRecordDecl *Current) {
1034 SmallVector<const CXXRecordDecl*, 8> Queue;
1035
1036 Class = Class->getCanonicalDecl();
1037 while (true) {
1038 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1039 E = Current->bases_end();
1040 I != E; ++I) {
1041 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1042 if (!Base)
1043 continue;
1044
1045 Base = Base->getDefinition();
1046 if (!Base)
1047 continue;
1048
1049 if (Base->getCanonicalDecl() == Class)
1050 return true;
1051
1052 Queue.push_back(Base);
1053 }
1054
1055 if (Queue.empty())
1056 return false;
1057
1058 Current = Queue.back();
1059 Queue.pop_back();
1060 }
1061
1062 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001063}
1064
Mike Stump1eb44332009-09-09 15:08:12 +00001065/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001066///
1067/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1068/// and returns NULL otherwise.
1069CXXBaseSpecifier *
1070Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1071 SourceRange SpecifierRange,
1072 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001073 TypeSourceInfo *TInfo,
1074 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001075 QualType BaseType = TInfo->getType();
1076
Douglas Gregor2943aed2009-03-03 04:44:36 +00001077 // C++ [class.union]p1:
1078 // A union shall not have base classes.
1079 if (Class->isUnion()) {
1080 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1081 << SpecifierRange;
1082 return 0;
1083 }
1084
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001085 if (EllipsisLoc.isValid() &&
1086 !TInfo->getType()->containsUnexpandedParameterPack()) {
1087 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1088 << TInfo->getTypeLoc().getSourceRange();
1089 EllipsisLoc = SourceLocation();
1090 }
Douglas Gregord777e282012-11-10 01:18:17 +00001091
1092 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1093
1094 if (BaseType->isDependentType()) {
1095 // Make sure that we don't have circular inheritance among our dependent
1096 // bases. For non-dependent bases, the check for completeness below handles
1097 // this.
1098 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1099 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1100 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001101 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001102 Diag(BaseLoc, diag::err_circular_inheritance)
1103 << BaseType << Context.getTypeDeclType(Class);
1104
1105 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1106 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1107 << BaseType;
1108
1109 return 0;
1110 }
1111 }
1112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001114 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001116 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117
1118 // Base specifiers must be record types.
1119 if (!BaseType->isRecordType()) {
1120 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1121 return 0;
1122 }
1123
1124 // C++ [class.union]p1:
1125 // A union shall not be used as a base class.
1126 if (BaseType->isUnionType()) {
1127 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1128 return 0;
1129 }
1130
1131 // C++ [class.derived]p2:
1132 // The class-name in a base-specifier shall not be an incompletely
1133 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001134 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001135 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001136 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001137 return 0;
John McCall572fc622010-08-17 07:23:57 +00001138 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139
Eli Friedman1d954f62009-08-15 21:55:26 +00001140 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001141 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001143 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001145 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1146 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001147
Anders Carlsson1d209272011-03-25 14:55:14 +00001148 // C++ [class]p3:
1149 // If a class is marked final and it appears as a base-type-specifier in
1150 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001151 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001152 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1153 << CXXBaseDecl->getDeclName();
1154 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1155 << CXXBaseDecl->getDeclName();
1156 return 0;
1157 }
1158
John McCall572fc622010-08-17 07:23:57 +00001159 if (BaseDecl->isInvalidDecl())
1160 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001161
1162 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001163 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001164 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001165 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001166}
1167
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001168/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1169/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001170/// example:
1171/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001172/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001173BaseResult
John McCalld226f652010-08-21 09:40:31 +00001174Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001175 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001176 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001177 ParsedType basetype, SourceLocation BaseLoc,
1178 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001179 if (!classdecl)
1180 return true;
1181
Douglas Gregor40808ce2009-03-09 23:48:35 +00001182 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001183 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001184 if (!Class)
1185 return true;
1186
Richard Smith05321402013-02-19 23:47:15 +00001187 // We do not support any C++11 attributes on base-specifiers yet.
1188 // Diagnose any attributes we see.
1189 if (!Attributes.empty()) {
1190 for (AttributeList *Attr = Attributes.getList(); Attr;
1191 Attr = Attr->getNext()) {
1192 if (Attr->isInvalid() ||
1193 Attr->getKind() == AttributeList::IgnoredAttribute)
1194 continue;
1195 Diag(Attr->getLoc(),
1196 Attr->getKind() == AttributeList::UnknownAttribute
1197 ? diag::warn_unknown_attribute_ignored
1198 : diag::err_base_specifier_attribute)
1199 << Attr->getName();
1200 }
1201 }
1202
Nick Lewycky56062202010-07-26 16:56:01 +00001203 TypeSourceInfo *TInfo = 0;
1204 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001205
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001206 if (EllipsisLoc.isInvalid() &&
1207 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001208 UPPC_BaseType))
1209 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001210
Douglas Gregor2943aed2009-03-03 04:44:36 +00001211 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001212 Virtual, Access, TInfo,
1213 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001214 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001215 else
1216 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregor2943aed2009-03-03 04:44:36 +00001218 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001219}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001220
Douglas Gregor2943aed2009-03-03 04:44:36 +00001221/// \brief Performs the actual work of attaching the given base class
1222/// specifiers to a C++ class.
1223bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1224 unsigned NumBases) {
1225 if (NumBases == 0)
1226 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001227
1228 // Used to keep track of which base types we have already seen, so
1229 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001230 // that the key is always the unqualified canonical type of the base
1231 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001232 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1233
1234 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001235 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001236 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001237 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001238 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001239 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001240 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001241
1242 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1243 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001244 // C++ [class.mi]p3:
1245 // A class shall not be specified as a direct base class of a
1246 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001247 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001248 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001249 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001250 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001251
1252 // Delete the duplicate base class specifier; we're going to
1253 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001254 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001255
1256 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001257 } else {
1258 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001259 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001261 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1262 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1263 if (Class->isInterface() &&
1264 (!RD->isInterface() ||
1265 KnownBase->getAccessSpecifier() != AS_public)) {
1266 // The Microsoft extension __interface does not permit bases that
1267 // are not themselves public interfaces.
1268 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1269 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1270 << RD->getSourceRange();
1271 Invalid = true;
1272 }
1273 if (RD->hasAttr<WeakAttr>())
1274 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1275 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001276 }
1277 }
1278
1279 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001280 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001281
1282 // Delete the remaining (good) base class specifiers, since their
1283 // data has been copied into the CXXRecordDecl.
1284 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001285 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 return Invalid;
1288}
1289
1290/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1291/// class, after checking whether there are any duplicate base
1292/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001293void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001294 unsigned NumBases) {
1295 if (!ClassDecl || !Bases || !NumBases)
1296 return;
1297
1298 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001299 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001300 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001301}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001302
John McCall3cb0ebd2010-03-10 03:28:59 +00001303static CXXRecordDecl *GetClassForType(QualType T) {
1304 if (const RecordType *RT = T->getAs<RecordType>())
1305 return cast<CXXRecordDecl>(RT->getDecl());
1306 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1307 return ICT->getDecl();
1308 else
1309 return 0;
1310}
1311
Douglas Gregora8f32e02009-10-06 17:59:45 +00001312/// \brief Determine whether the type \p Derived is a C++ class that is
1313/// derived from the type \p Base.
1314bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001315 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001316 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001317
1318 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1319 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001320 return false;
1321
John McCall3cb0ebd2010-03-10 03:28:59 +00001322 CXXRecordDecl *BaseRD = GetClassForType(Base);
1323 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001324 return false;
1325
John McCall86ff3082010-02-04 22:26:26 +00001326 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1327 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001328}
1329
1330/// \brief Determine whether the type \p Derived is a C++ class that is
1331/// derived from the type \p Base.
1332bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001333 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001334 return false;
1335
John McCall3cb0ebd2010-03-10 03:28:59 +00001336 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1337 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001338 return false;
1339
John McCall3cb0ebd2010-03-10 03:28:59 +00001340 CXXRecordDecl *BaseRD = GetClassForType(Base);
1341 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001342 return false;
1343
Douglas Gregora8f32e02009-10-06 17:59:45 +00001344 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1345}
1346
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001347void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001348 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001349 assert(BasePathArray.empty() && "Base path array must be empty!");
1350 assert(Paths.isRecordingPaths() && "Must record paths!");
1351
1352 const CXXBasePath &Path = Paths.front();
1353
1354 // We first go backward and check if we have a virtual base.
1355 // FIXME: It would be better if CXXBasePath had the base specifier for
1356 // the nearest virtual base.
1357 unsigned Start = 0;
1358 for (unsigned I = Path.size(); I != 0; --I) {
1359 if (Path[I - 1].Base->isVirtual()) {
1360 Start = I - 1;
1361 break;
1362 }
1363 }
1364
1365 // Now add all bases.
1366 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001367 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001368}
1369
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001370/// \brief Determine whether the given base path includes a virtual
1371/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001372bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1373 for (CXXCastPath::const_iterator B = BasePath.begin(),
1374 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001375 B != BEnd; ++B)
1376 if ((*B)->isVirtual())
1377 return true;
1378
1379 return false;
1380}
1381
Douglas Gregora8f32e02009-10-06 17:59:45 +00001382/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1383/// conversion (where Derived and Base are class types) is
1384/// well-formed, meaning that the conversion is unambiguous (and
1385/// that all of the base classes are accessible). Returns true
1386/// and emits a diagnostic if the code is ill-formed, returns false
1387/// otherwise. Loc is the location where this routine should point to
1388/// if there is an error, and Range is the source range to highlight
1389/// if there is an error.
1390bool
1391Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001392 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001393 unsigned AmbigiousBaseConvID,
1394 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001395 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001396 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001397 // First, determine whether the path from Derived to Base is
1398 // ambiguous. This is slightly more expensive than checking whether
1399 // the Derived to Base conversion exists, because here we need to
1400 // explore multiple paths to determine if there is an ambiguity.
1401 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1402 /*DetectVirtual=*/false);
1403 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1404 assert(DerivationOkay &&
1405 "Can only be used with a derived-to-base conversion");
1406 (void)DerivationOkay;
1407
1408 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001409 if (InaccessibleBaseID) {
1410 // Check that the base class can be accessed.
1411 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1412 InaccessibleBaseID)) {
1413 case AR_inaccessible:
1414 return true;
1415 case AR_accessible:
1416 case AR_dependent:
1417 case AR_delayed:
1418 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001419 }
John McCall6b2accb2010-02-10 09:31:12 +00001420 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001421
1422 // Build a base path if necessary.
1423 if (BasePath)
1424 BuildBasePathArray(Paths, *BasePath);
1425 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001426 }
1427
1428 // We know that the derived-to-base conversion is ambiguous, and
1429 // we're going to produce a diagnostic. Perform the derived-to-base
1430 // search just one more time to compute all of the possible paths so
1431 // that we can print them out. This is more expensive than any of
1432 // the previous derived-to-base checks we've done, but at this point
1433 // performance isn't as much of an issue.
1434 Paths.clear();
1435 Paths.setRecordingPaths(true);
1436 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1437 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1438 (void)StillOkay;
1439
1440 // Build up a textual representation of the ambiguous paths, e.g.,
1441 // D -> B -> A, that will be used to illustrate the ambiguous
1442 // conversions in the diagnostic. We only print one of the paths
1443 // to each base class subobject.
1444 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1445
1446 Diag(Loc, AmbigiousBaseConvID)
1447 << Derived << Base << PathDisplayStr << Range << Name;
1448 return true;
1449}
1450
1451bool
1452Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001453 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001454 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001455 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001456 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001457 IgnoreAccess ? 0
1458 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001459 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001460 Loc, Range, DeclarationName(),
1461 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001462}
1463
1464
1465/// @brief Builds a string representing ambiguous paths from a
1466/// specific derived class to different subobjects of the same base
1467/// class.
1468///
1469/// This function builds a string that can be used in error messages
1470/// to show the different paths that one can take through the
1471/// inheritance hierarchy to go from the derived class to different
1472/// subobjects of a base class. The result looks something like this:
1473/// @code
1474/// struct D -> struct B -> struct A
1475/// struct D -> struct C -> struct A
1476/// @endcode
1477std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1478 std::string PathDisplayStr;
1479 std::set<unsigned> DisplayedPaths;
1480 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1481 Path != Paths.end(); ++Path) {
1482 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1483 // We haven't displayed a path to this particular base
1484 // class subobject yet.
1485 PathDisplayStr += "\n ";
1486 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1487 for (CXXBasePath::const_iterator Element = Path->begin();
1488 Element != Path->end(); ++Element)
1489 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1490 }
1491 }
1492
1493 return PathDisplayStr;
1494}
1495
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001496//===----------------------------------------------------------------------===//
1497// C++ class member Handling
1498//===----------------------------------------------------------------------===//
1499
Abramo Bagnara6206d532010-06-05 05:09:32 +00001500/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001501bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1502 SourceLocation ASLoc,
1503 SourceLocation ColonLoc,
1504 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001505 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001506 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001507 ASLoc, ColonLoc);
1508 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001509 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001510}
1511
Richard Smitha4b39652012-08-06 03:25:17 +00001512/// CheckOverrideControl - Check C++11 override control semantics.
1513void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001514 if (D->isInvalidDecl())
1515 return;
1516
Chris Lattner5f9e2722011-07-23 10:55:15 +00001517 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001518
Richard Smitha4b39652012-08-06 03:25:17 +00001519 // Do we know which functions this declaration might be overriding?
1520 bool OverridesAreKnown = !MD ||
1521 (!MD->getParent()->hasAnyDependentBases() &&
1522 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001523
Richard Smitha4b39652012-08-06 03:25:17 +00001524 if (!MD || !MD->isVirtual()) {
1525 if (OverridesAreKnown) {
1526 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1527 Diag(OA->getLocation(),
1528 diag::override_keyword_only_allowed_on_virtual_member_functions)
1529 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1530 D->dropAttr<OverrideAttr>();
1531 }
1532 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1533 Diag(FA->getLocation(),
1534 diag::override_keyword_only_allowed_on_virtual_member_functions)
1535 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1536 D->dropAttr<FinalAttr>();
1537 }
1538 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001539 return;
1540 }
Richard Smitha4b39652012-08-06 03:25:17 +00001541
1542 if (!OverridesAreKnown)
1543 return;
1544
1545 // C++11 [class.virtual]p5:
1546 // If a virtual function is marked with the virt-specifier override and
1547 // does not override a member function of a base class, the program is
1548 // ill-formed.
1549 bool HasOverriddenMethods =
1550 MD->begin_overridden_methods() != MD->end_overridden_methods();
1551 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1552 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1553 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001554}
1555
Richard Smitha4b39652012-08-06 03:25:17 +00001556/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001557/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001558/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001559bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1560 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001561 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001562 return false;
1563
1564 Diag(New->getLocation(), diag::err_final_function_overridden)
1565 << New->getDeclName();
1566 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1567 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001568}
1569
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001570static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001571 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1572 // FIXME: Destruction of ObjC lifetime types has side-effects.
1573 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1574 return !RD->isCompleteDefinition() ||
1575 !RD->hasTrivialDefaultConstructor() ||
1576 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001577 return false;
1578}
1579
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001580/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1581/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001582/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001583/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1584/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001585NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001586Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001587 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001588 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001589 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001590 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001591 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1592 DeclarationName Name = NameInfo.getName();
1593 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001594
1595 // For anonymous bitfields, the location should point to the type.
1596 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001597 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001598
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001599 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001600
John McCall4bde1e12010-06-04 08:34:12 +00001601 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001602 assert(!DS.isFriendSpecified());
1603
Richard Smith1ab0d902011-06-25 02:28:38 +00001604 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001605
John McCalle402e722012-09-25 07:32:39 +00001606 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1607 // The Microsoft extension __interface only permits public member functions
1608 // and prohibits constructors, destructors, operators, non-public member
1609 // functions, static methods and data members.
1610 unsigned InvalidDecl;
1611 bool ShowDeclName = true;
1612 if (!isFunc)
1613 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1614 else if (AS != AS_public)
1615 InvalidDecl = 2;
1616 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1617 InvalidDecl = 3;
1618 else switch (Name.getNameKind()) {
1619 case DeclarationName::CXXConstructorName:
1620 InvalidDecl = 4;
1621 ShowDeclName = false;
1622 break;
1623
1624 case DeclarationName::CXXDestructorName:
1625 InvalidDecl = 5;
1626 ShowDeclName = false;
1627 break;
1628
1629 case DeclarationName::CXXOperatorName:
1630 case DeclarationName::CXXConversionFunctionName:
1631 InvalidDecl = 6;
1632 break;
1633
1634 default:
1635 InvalidDecl = 0;
1636 break;
1637 }
1638
1639 if (InvalidDecl) {
1640 if (ShowDeclName)
1641 Diag(Loc, diag::err_invalid_member_in_interface)
1642 << (InvalidDecl-1) << Name;
1643 else
1644 Diag(Loc, diag::err_invalid_member_in_interface)
1645 << (InvalidDecl-1) << "";
1646 return 0;
1647 }
1648 }
1649
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001650 // C++ 9.2p6: A member shall not be declared to have automatic storage
1651 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001652 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1653 // data members and cannot be applied to names declared const or static,
1654 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001655 switch (DS.getStorageClassSpec()) {
1656 case DeclSpec::SCS_unspecified:
1657 case DeclSpec::SCS_typedef:
1658 case DeclSpec::SCS_static:
1659 // FALL THROUGH.
1660 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001661 case DeclSpec::SCS_mutable:
1662 if (isFunc) {
1663 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001664 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001665 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001666 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Sebastian Redla11f42f2008-11-17 23:24:37 +00001668 // FIXME: It would be nicer if the keyword was ignored only for this
1669 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001670 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001671 }
1672 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001673 default:
1674 if (DS.getStorageClassSpecLoc().isValid())
1675 Diag(DS.getStorageClassSpecLoc(),
1676 diag::err_storageclass_invalid_for_member);
1677 else
1678 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1679 D.getMutableDeclSpec().ClearStorageClassSpecs();
1680 }
1681
Sebastian Redl669d5d72008-11-14 23:42:31 +00001682 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1683 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001684 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001685
David Blaikie1d87fba2013-01-30 01:22:18 +00001686 if (DS.isConstexprSpecified() && isInstField) {
1687 SemaDiagnosticBuilder B =
1688 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1689 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1690 if (InitStyle == ICIS_NoInit) {
1691 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1692 D.getMutableDeclSpec().ClearConstexprSpec();
1693 const char *PrevSpec;
1694 unsigned DiagID;
1695 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1696 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001697 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001698 assert(!Failed && "Making a constexpr member const shouldn't fail");
1699 } else {
1700 B << 1;
1701 const char *PrevSpec;
1702 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001703 if (D.getMutableDeclSpec().SetStorageClassSpec(
1704 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001705 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001706 "This is the only DeclSpec that should fail to be applied");
1707 B << 1;
1708 } else {
1709 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1710 isInstField = false;
1711 }
1712 }
1713 }
1714
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001715 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001716 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001717 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001718
1719 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001720 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001721 Diag(Loc, diag::err_bad_variable_name)
1722 << Name;
1723 return 0;
1724 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001725
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001726 IdentifierInfo *II = Name.getAsIdentifierInfo();
1727
Douglas Gregorf2503652011-09-21 14:40:46 +00001728 // Member field could not be with "template" keyword.
1729 // So TemplateParameterLists should be empty in this case.
1730 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001731 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001732 if (TemplateParams->size()) {
1733 // There is no such thing as a member field template.
1734 Diag(D.getIdentifierLoc(), diag::err_template_member)
1735 << II
1736 << SourceRange(TemplateParams->getTemplateLoc(),
1737 TemplateParams->getRAngleLoc());
1738 } else {
1739 // There is an extraneous 'template<>' for this member.
1740 Diag(TemplateParams->getTemplateLoc(),
1741 diag::err_template_member_noparams)
1742 << II
1743 << SourceRange(TemplateParams->getTemplateLoc(),
1744 TemplateParams->getRAngleLoc());
1745 }
1746 return 0;
1747 }
1748
Douglas Gregor922fff22010-10-13 22:19:53 +00001749 if (SS.isSet() && !SS.isInvalid()) {
1750 // The user provided a superfluous scope specifier inside a class
1751 // definition:
1752 //
1753 // class X {
1754 // int X::member;
1755 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001756 if (DeclContext *DC = computeDeclContext(SS, false))
1757 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001758 else
1759 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1760 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001761
Douglas Gregor922fff22010-10-13 22:19:53 +00001762 SS.clear();
1763 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001764
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001765 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001766 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001767 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001768 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001769 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001770
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001771 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001772 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001773 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001774 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001775
1776 // Non-instance-fields can't have a bitfield.
1777 if (BitWidth) {
1778 if (Member->isInvalidDecl()) {
1779 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001780 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001781 // C++ 9.6p3: A bit-field shall not be a static member.
1782 // "static member 'A' cannot be a bit-field"
1783 Diag(Loc, diag::err_static_not_bitfield)
1784 << Name << BitWidth->getSourceRange();
1785 } else if (isa<TypedefDecl>(Member)) {
1786 // "typedef member 'x' cannot be a bit-field"
1787 Diag(Loc, diag::err_typedef_not_bitfield)
1788 << Name << BitWidth->getSourceRange();
1789 } else {
1790 // A function typedef ("typedef int f(); f a;").
1791 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1792 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001793 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001794 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001795 }
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Chris Lattner8b963ef2009-03-05 23:01:03 +00001797 BitWidth = 0;
1798 Member->setInvalidDecl();
1799 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001800
1801 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Douglas Gregor37b372b2009-08-20 22:52:58 +00001803 // If we have declared a member function template, set the access of the
1804 // templated declaration as well.
1805 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1806 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001807 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001808
Richard Smitha4b39652012-08-06 03:25:17 +00001809 if (VS.isOverrideSpecified())
1810 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1811 if (VS.isFinalSpecified())
1812 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001813
Douglas Gregorf5251602011-03-08 17:10:18 +00001814 if (VS.getLastLocation().isValid()) {
1815 // Update the end location of a method that has a virt-specifiers.
1816 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1817 MD->setRangeEnd(VS.getLastLocation());
1818 }
Richard Smitha4b39652012-08-06 03:25:17 +00001819
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001820 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001821
Douglas Gregor10bd3682008-11-17 22:58:34 +00001822 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001823
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001824 if (isInstField) {
1825 FieldDecl *FD = cast<FieldDecl>(Member);
1826 FieldCollector->Add(FD);
1827
1828 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1829 FD->getLocation())
1830 != DiagnosticsEngine::Ignored) {
1831 // Remember all explicit private FieldDecls that have a name, no side
1832 // effects and are not part of a dependent type declaration.
1833 if (!FD->isImplicit() && FD->getDeclName() &&
1834 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001835 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001836 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001837 !InitializationHasSideEffects(*FD))
1838 UnusedPrivateFields.insert(FD);
1839 }
1840 }
1841
John McCalld226f652010-08-21 09:40:31 +00001842 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001843}
1844
Hans Wennborg471f9852012-09-18 15:58:06 +00001845namespace {
1846 class UninitializedFieldVisitor
1847 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1848 Sema &S;
1849 ValueDecl *VD;
1850 public:
1851 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1852 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001853 S(S) {
1854 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1855 this->VD = IFD->getAnonField();
1856 else
1857 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001858 }
1859
1860 void HandleExpr(Expr *E) {
1861 if (!E) return;
1862
1863 // Expressions like x(x) sometimes lack the surrounding expressions
1864 // but need to be checked anyways.
1865 HandleValue(E);
1866 Visit(E);
1867 }
1868
1869 void HandleValue(Expr *E) {
1870 E = E->IgnoreParens();
1871
1872 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1873 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001874 return;
1875
1876 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1877 // or union.
1878 MemberExpr *FieldME = ME;
1879
Hans Wennborg471f9852012-09-18 15:58:06 +00001880 Expr *Base = E;
1881 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001882 ME = cast<MemberExpr>(Base);
1883
1884 if (isa<VarDecl>(ME->getMemberDecl()))
1885 return;
1886
1887 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1888 if (!FD->isAnonymousStructOrUnion())
1889 FieldME = ME;
1890
Hans Wennborg471f9852012-09-18 15:58:06 +00001891 Base = ME->getBase();
1892 }
1893
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001894 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001895 unsigned diag = VD->getType()->isReferenceType()
1896 ? diag::warn_reference_field_is_uninit
1897 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001898 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001899 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001900 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001901 }
1902
1903 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1904 HandleValue(CO->getTrueExpr());
1905 HandleValue(CO->getFalseExpr());
1906 return;
1907 }
1908
1909 if (BinaryConditionalOperator *BCO =
1910 dyn_cast<BinaryConditionalOperator>(E)) {
1911 HandleValue(BCO->getCommon());
1912 HandleValue(BCO->getFalseExpr());
1913 return;
1914 }
1915
1916 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1917 switch (BO->getOpcode()) {
1918 default:
1919 return;
1920 case(BO_PtrMemD):
1921 case(BO_PtrMemI):
1922 HandleValue(BO->getLHS());
1923 return;
1924 case(BO_Comma):
1925 HandleValue(BO->getRHS());
1926 return;
1927 }
1928 }
1929 }
1930
1931 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1932 if (E->getCastKind() == CK_LValueToRValue)
1933 HandleValue(E->getSubExpr());
1934
1935 Inherited::VisitImplicitCastExpr(E);
1936 }
1937
1938 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1939 Expr *Callee = E->getCallee();
1940 if (isa<MemberExpr>(Callee))
1941 HandleValue(Callee);
1942
1943 Inherited::VisitCXXMemberCallExpr(E);
1944 }
1945 };
1946 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1947 ValueDecl *VD) {
1948 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1949 }
1950} // namespace
1951
Richard Smith7a614d82011-06-11 17:19:42 +00001952/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001953/// in-class initializer for a non-static C++ class member, and after
1954/// instantiating an in-class initializer in a class template. Such actions
1955/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001956void
Richard Smithca523302012-06-10 03:12:00 +00001957Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001958 Expr *InitExpr) {
1959 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001960 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1961 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001962
1963 if (!InitExpr) {
1964 FD->setInvalidDecl();
1965 FD->removeInClassInitializer();
1966 return;
1967 }
1968
Peter Collingbournefef21892011-10-23 18:59:44 +00001969 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1970 FD->setInvalidDecl();
1971 FD->removeInClassInitializer();
1972 return;
1973 }
1974
Hans Wennborg471f9852012-09-18 15:58:06 +00001975 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1976 != DiagnosticsEngine::Ignored) {
1977 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1978 }
1979
Richard Smith7a614d82011-06-11 17:19:42 +00001980 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001981 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001982 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001983 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001984 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1985 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001986 Expr **Inits = &InitExpr;
1987 unsigned NumInits = 1;
1988 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001989 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001990 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001991 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001992 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1993 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001994 if (Init.isInvalid()) {
1995 FD->setInvalidDecl();
1996 return;
1997 }
Richard Smith7a614d82011-06-11 17:19:42 +00001998 }
1999
Richard Smith41956372013-01-14 22:39:08 +00002000 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002001 // The initialization of each base and member constitutes a
2002 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002003 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002004 if (Init.isInvalid()) {
2005 FD->setInvalidDecl();
2006 return;
2007 }
2008
2009 InitExpr = Init.release();
2010
2011 FD->setInClassInitializer(InitExpr);
2012}
2013
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002014/// \brief Find the direct and/or virtual base specifiers that
2015/// correspond to the given base type, for use in base initialization
2016/// within a constructor.
2017static bool FindBaseInitializer(Sema &SemaRef,
2018 CXXRecordDecl *ClassDecl,
2019 QualType BaseType,
2020 const CXXBaseSpecifier *&DirectBaseSpec,
2021 const CXXBaseSpecifier *&VirtualBaseSpec) {
2022 // First, check for a direct base class.
2023 DirectBaseSpec = 0;
2024 for (CXXRecordDecl::base_class_const_iterator Base
2025 = ClassDecl->bases_begin();
2026 Base != ClassDecl->bases_end(); ++Base) {
2027 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2028 // We found a direct base of this type. That's what we're
2029 // initializing.
2030 DirectBaseSpec = &*Base;
2031 break;
2032 }
2033 }
2034
2035 // Check for a virtual base class.
2036 // FIXME: We might be able to short-circuit this if we know in advance that
2037 // there are no virtual bases.
2038 VirtualBaseSpec = 0;
2039 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2040 // We haven't found a base yet; search the class hierarchy for a
2041 // virtual base class.
2042 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2043 /*DetectVirtual=*/false);
2044 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2045 BaseType, Paths)) {
2046 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2047 Path != Paths.end(); ++Path) {
2048 if (Path->back().Base->isVirtual()) {
2049 VirtualBaseSpec = Path->back().Base;
2050 break;
2051 }
2052 }
2053 }
2054 }
2055
2056 return DirectBaseSpec || VirtualBaseSpec;
2057}
2058
Sebastian Redl6df65482011-09-24 17:48:25 +00002059/// \brief Handle a C++ member initializer using braced-init-list syntax.
2060MemInitResult
2061Sema::ActOnMemInitializer(Decl *ConstructorD,
2062 Scope *S,
2063 CXXScopeSpec &SS,
2064 IdentifierInfo *MemberOrBase,
2065 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002066 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002067 SourceLocation IdLoc,
2068 Expr *InitList,
2069 SourceLocation EllipsisLoc) {
2070 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002071 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002072 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002073}
2074
2075/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002076MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002077Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002078 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002079 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002080 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002081 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002082 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002083 SourceLocation IdLoc,
2084 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002085 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002086 SourceLocation RParenLoc,
2087 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002088 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2089 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002090 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002092 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002093}
2094
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002095namespace {
2096
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002097// Callback to only accept typo corrections that can be a valid C++ member
2098// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002099class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2100 public:
2101 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2102 : ClassDecl(ClassDecl) {}
2103
2104 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2106 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2107 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2108 else
2109 return isa<TypeDecl>(ND);
2110 }
2111 return false;
2112 }
2113
2114 private:
2115 CXXRecordDecl *ClassDecl;
2116};
2117
2118}
2119
Sebastian Redl6df65482011-09-24 17:48:25 +00002120/// \brief Handle a C++ member initializer.
2121MemInitResult
2122Sema::BuildMemInitializer(Decl *ConstructorD,
2123 Scope *S,
2124 CXXScopeSpec &SS,
2125 IdentifierInfo *MemberOrBase,
2126 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002127 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002128 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002129 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002130 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002131 if (!ConstructorD)
2132 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002134 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002135
2136 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002137 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002138 if (!Constructor) {
2139 // The user wrote a constructor initializer on a function that is
2140 // not a C++ constructor. Ignore the error for now, because we may
2141 // have more member initializers coming; we'll diagnose it just
2142 // once in ActOnMemInitializers.
2143 return true;
2144 }
2145
2146 CXXRecordDecl *ClassDecl = Constructor->getParent();
2147
2148 // C++ [class.base.init]p2:
2149 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002150 // constructor's class and, if not found in that scope, are looked
2151 // up in the scope containing the constructor's definition.
2152 // [Note: if the constructor's class contains a member with the
2153 // same name as a direct or virtual base class of the class, a
2154 // mem-initializer-id naming the member or base class and composed
2155 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002156 // mem-initializer-id for the hidden base class may be specified
2157 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002158 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002159 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002160 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002161 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002162 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002163 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002164 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2165 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002166 if (EllipsisLoc.isValid())
2167 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002168 << MemberOrBase
2169 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002170
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002171 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002172 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002173 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002174 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002175 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002176 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002177 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002178
2179 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002180 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002181 } else if (DS.getTypeSpecType() == TST_decltype) {
2182 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002183 } else {
2184 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2185 LookupParsedName(R, S, &SS);
2186
2187 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2188 if (!TyD) {
2189 if (R.isAmbiguous()) return true;
2190
John McCallfd225442010-04-09 19:01:14 +00002191 // We don't want access-control diagnostics here.
2192 R.suppressDiagnostics();
2193
Douglas Gregor7a886e12010-01-19 06:46:48 +00002194 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2195 bool NotUnknownSpecialization = false;
2196 DeclContext *DC = computeDeclContext(SS, false);
2197 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2198 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2199
2200 if (!NotUnknownSpecialization) {
2201 // When the scope specifier can refer to a member of an unknown
2202 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002203 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2204 SS.getWithLocInContext(Context),
2205 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002206 if (BaseType.isNull())
2207 return true;
2208
Douglas Gregor7a886e12010-01-19 06:46:48 +00002209 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002210 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002211 }
2212 }
2213
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002214 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002215 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002216 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002217 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002218 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002219 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002220 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2221 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002222 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002223 // We have found a non-static data member with a similar
2224 // name to what was typed; complain and initialize that
2225 // member.
2226 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2227 << MemberOrBase << true << CorrectedQuotedStr
2228 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2229 Diag(Member->getLocation(), diag::note_previous_decl)
2230 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002231
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002232 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002233 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002234 const CXXBaseSpecifier *DirectBaseSpec;
2235 const CXXBaseSpecifier *VirtualBaseSpec;
2236 if (FindBaseInitializer(*this, ClassDecl,
2237 Context.getTypeDeclType(Type),
2238 DirectBaseSpec, VirtualBaseSpec)) {
2239 // We have found a direct or virtual base class with a
2240 // similar name to what was typed; complain and initialize
2241 // that base class.
2242 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002243 << MemberOrBase << false << CorrectedQuotedStr
2244 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002245
2246 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2247 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002248 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002249 diag::note_base_class_specified_here)
2250 << BaseSpec->getType()
2251 << BaseSpec->getSourceRange();
2252
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002253 TyD = Type;
2254 }
2255 }
2256 }
2257
Douglas Gregor7a886e12010-01-19 06:46:48 +00002258 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002259 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002260 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002261 return true;
2262 }
John McCall2b194412009-12-21 10:41:20 +00002263 }
2264
Douglas Gregor7a886e12010-01-19 06:46:48 +00002265 if (BaseType.isNull()) {
2266 BaseType = Context.getTypeDeclType(TyD);
2267 if (SS.isSet()) {
2268 NestedNameSpecifier *Qualifier =
2269 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002270
Douglas Gregor7a886e12010-01-19 06:46:48 +00002271 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002272 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002273 }
John McCall2b194412009-12-21 10:41:20 +00002274 }
2275 }
Mike Stump1eb44332009-09-09 15:08:12 +00002276
John McCalla93c9342009-12-07 02:54:59 +00002277 if (!TInfo)
2278 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002279
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002280 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002281}
2282
Chandler Carruth81c64772011-09-03 01:14:15 +00002283/// Checks a member initializer expression for cases where reference (or
2284/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002285static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2286 Expr *Init,
2287 SourceLocation IdLoc) {
2288 QualType MemberTy = Member->getType();
2289
2290 // We only handle pointers and references currently.
2291 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2292 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2293 return;
2294
2295 const bool IsPointer = MemberTy->isPointerType();
2296 if (IsPointer) {
2297 if (const UnaryOperator *Op
2298 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2299 // The only case we're worried about with pointers requires taking the
2300 // address.
2301 if (Op->getOpcode() != UO_AddrOf)
2302 return;
2303
2304 Init = Op->getSubExpr();
2305 } else {
2306 // We only handle address-of expression initializers for pointers.
2307 return;
2308 }
2309 }
2310
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002311 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2312 // Taking the address of a temporary will be diagnosed as a hard error.
2313 if (IsPointer)
2314 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002315
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002316 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2317 << Member << Init->getSourceRange();
2318 } else if (const DeclRefExpr *DRE
2319 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2320 // We only warn when referring to a non-reference parameter declaration.
2321 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2322 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002323 return;
2324
2325 S.Diag(Init->getExprLoc(),
2326 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2327 : diag::warn_bind_ref_member_to_parameter)
2328 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002329 } else {
2330 // Other initializers are fine.
2331 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002332 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002333
2334 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2335 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002336}
2337
John McCallf312b1e2010-08-26 23:41:50 +00002338MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002340 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002341 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2342 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2343 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002344 "Member must be a FieldDecl or IndirectFieldDecl");
2345
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002346 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002347 return true;
2348
Douglas Gregor464b2f02010-11-05 22:21:31 +00002349 if (Member->isInvalidDecl())
2350 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002351
John McCallb4190042009-11-04 23:02:40 +00002352 // Diagnose value-uses of fields to initialize themselves, e.g.
2353 // foo(foo)
2354 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002355 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002356 Expr **Args;
2357 unsigned NumArgs;
2358 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2359 Args = ParenList->getExprs();
2360 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002361 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002362 Args = InitList->getInits();
2363 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002364 } else {
2365 // Template instantiation doesn't reconstruct ParenListExprs for us.
2366 Args = &Init;
2367 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002369
Richard Trieude5e75c2012-06-14 23:11:34 +00002370 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2371 != DiagnosticsEngine::Ignored)
2372 for (unsigned i = 0; i < NumArgs; ++i)
2373 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002374 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002375 // initializing the i'th field, throw a warning if any of the >= i'th
2376 // fields are used, as they are not yet initialized.
2377 // Right now we are only handling the case where the i'th field uses
2378 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002379 // Also need to take into account that some fields may be initialized by
2380 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002381 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002382
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002383 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002384
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002385 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002386 // Can't check initialization for a member of dependent type or when
2387 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002388 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002389 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002390 bool InitList = false;
2391 if (isa<InitListExpr>(Init)) {
2392 InitList = true;
2393 Args = &Init;
2394 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002395
2396 if (isStdInitializerList(Member->getType(), 0)) {
2397 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2398 << /*at end of ctor*/1 << InitRange;
2399 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002400 }
2401
Chandler Carruth894aed92010-12-06 09:23:57 +00002402 // Initialize the member.
2403 InitializedEntity MemberEntity =
2404 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2405 : InitializedEntity::InitializeMember(IndirectMember, 0);
2406 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002407 InitList ? InitializationKind::CreateDirectList(IdLoc)
2408 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2409 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002410
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002411 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2412 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002413 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002414 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002415 if (MemberInit.isInvalid())
2416 return true;
2417
Richard Smith41956372013-01-14 22:39:08 +00002418 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002419 // The initialization of each base and member constitutes a
2420 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002421 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002422 if (MemberInit.isInvalid())
2423 return true;
2424
Richard Smithc83c2302012-12-19 01:39:02 +00002425 Init = MemberInit.get();
2426 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002427 }
2428
Chandler Carruth894aed92010-12-06 09:23:57 +00002429 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002430 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2431 InitRange.getBegin(), Init,
2432 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002433 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002434 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2435 InitRange.getBegin(), Init,
2436 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002437 }
Eli Friedman59c04372009-07-29 19:44:27 +00002438}
2439
John McCallf312b1e2010-08-26 23:41:50 +00002440MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002442 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002443 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002444 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002445 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002446 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002447 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002448
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002449 bool InitList = true;
2450 Expr **Args = &Init;
2451 unsigned NumArgs = 1;
2452 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2453 InitList = false;
2454 Args = ParenList->getExprs();
2455 NumArgs = ParenList->getNumExprs();
2456 }
2457
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002458 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002459 // Initialize the object.
2460 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2461 QualType(ClassDecl->getTypeForDecl(), 0));
2462 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002463 InitList ? InitializationKind::CreateDirectList(NameLoc)
2464 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2465 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002466 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2467 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002468 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002469 0);
Sean Hunt41717662011-02-26 19:13:13 +00002470 if (DelegationInit.isInvalid())
2471 return true;
2472
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002473 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2474 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002475
Richard Smith41956372013-01-14 22:39:08 +00002476 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002477 // The initialization of each base and member constitutes a
2478 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002479 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2480 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002481 if (DelegationInit.isInvalid())
2482 return true;
2483
Eli Friedmand21016f2012-05-19 23:35:23 +00002484 // If we are in a dependent context, template instantiation will
2485 // perform this type-checking again. Just save the arguments that we
2486 // received in a ParenListExpr.
2487 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2488 // of the information that we have about the base
2489 // initializer. However, deconstructing the ASTs is a dicey process,
2490 // and this approach is far more likely to get the corner cases right.
2491 if (CurContext->isDependentContext())
2492 DelegationInit = Owned(Init);
2493
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002494 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002495 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002496 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002497}
2498
2499MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002500Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002501 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002502 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002503 SourceLocation BaseLoc
2504 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002505
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002506 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2507 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2508 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2509
2510 // C++ [class.base.init]p2:
2511 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002512 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002513 // of that class, the mem-initializer is ill-formed. A
2514 // mem-initializer-list can initialize a base class using any
2515 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002516 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002517
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002518 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002519 if (EllipsisLoc.isValid()) {
2520 // This is a pack expansion.
2521 if (!BaseType->containsUnexpandedParameterPack()) {
2522 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002523 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002524
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002525 EllipsisLoc = SourceLocation();
2526 }
2527 } else {
2528 // Check for any unexpanded parameter packs.
2529 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2530 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002531
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002532 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002533 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002534 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002535
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002536 // Check for direct and virtual base classes.
2537 const CXXBaseSpecifier *DirectBaseSpec = 0;
2538 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2539 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002540 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2541 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002542 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002543
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002544 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2545 VirtualBaseSpec);
2546
2547 // C++ [base.class.init]p2:
2548 // Unless the mem-initializer-id names a nonstatic data member of the
2549 // constructor's class or a direct or virtual base of that class, the
2550 // mem-initializer is ill-formed.
2551 if (!DirectBaseSpec && !VirtualBaseSpec) {
2552 // If the class has any dependent bases, then it's possible that
2553 // one of those types will resolve to the same type as
2554 // BaseType. Therefore, just treat this as a dependent base
2555 // class initialization. FIXME: Should we try to check the
2556 // initialization anyway? It seems odd.
2557 if (ClassDecl->hasAnyDependentBases())
2558 Dependent = true;
2559 else
2560 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2561 << BaseType << Context.getTypeDeclType(ClassDecl)
2562 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2563 }
2564 }
2565
2566 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002567 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Sebastian Redl6df65482011-09-24 17:48:25 +00002569 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2570 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002571 InitRange.getBegin(), Init,
2572 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002573 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002574
2575 // C++ [base.class.init]p2:
2576 // If a mem-initializer-id is ambiguous because it designates both
2577 // a direct non-virtual base class and an inherited virtual base
2578 // class, the mem-initializer is ill-formed.
2579 if (DirectBaseSpec && VirtualBaseSpec)
2580 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002581 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002582
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002583 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002584 if (!BaseSpec)
2585 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2586
2587 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002588 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002589 Expr **Args = &Init;
2590 unsigned NumArgs = 1;
2591 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002592 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002593 Args = ParenList->getExprs();
2594 NumArgs = ParenList->getNumExprs();
2595 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002596
2597 InitializedEntity BaseEntity =
2598 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2599 InitializationKind Kind =
2600 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2601 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2602 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002603 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2604 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002605 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002606 if (BaseInit.isInvalid())
2607 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002608
Richard Smith41956372013-01-14 22:39:08 +00002609 // C++11 [class.base.init]p7:
2610 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002611 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002612 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002613 if (BaseInit.isInvalid())
2614 return true;
2615
2616 // If we are in a dependent context, template instantiation will
2617 // perform this type-checking again. Just save the arguments that we
2618 // received in a ParenListExpr.
2619 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2620 // of the information that we have about the base
2621 // initializer. However, deconstructing the ASTs is a dicey process,
2622 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002623 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002624 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002625
Sean Huntcbb67482011-01-08 20:30:50 +00002626 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002627 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002628 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002629 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002630 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002631}
2632
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002633// Create a static_cast\<T&&>(expr).
2634static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2635 QualType ExprType = E->getType();
2636 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2637 SourceLocation ExprLoc = E->getLocStart();
2638 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2639 TargetType, ExprLoc);
2640
2641 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2642 SourceRange(ExprLoc, ExprLoc),
2643 E->getSourceRange()).take();
2644}
2645
Anders Carlssone5ef7402010-04-23 03:10:23 +00002646/// ImplicitInitializerKind - How an implicit base or member initializer should
2647/// initialize its base or member.
2648enum ImplicitInitializerKind {
2649 IIK_Default,
2650 IIK_Copy,
2651 IIK_Move
2652};
2653
Anders Carlssondefefd22010-04-23 02:00:02 +00002654static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002655BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002656 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002657 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002658 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002659 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002660 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002661 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2662 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002663
John McCall60d7b3a2010-08-24 06:29:42 +00002664 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002665
2666 switch (ImplicitInitKind) {
2667 case IIK_Default: {
2668 InitializationKind InitKind
2669 = InitializationKind::CreateDefault(Constructor->getLocation());
2670 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002671 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002672 break;
2673 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002674
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002675 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002676 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002678 ParmVarDecl *Param = Constructor->getParamDecl(0);
2679 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002680
Anders Carlssone5ef7402010-04-23 03:10:23 +00002681 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002682 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002683 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002684 Constructor->getLocation(), ParamType,
2685 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002686
Eli Friedman5f2987c2012-02-02 03:46:19 +00002687 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2688
Anders Carlssonc7957502010-04-24 22:02:54 +00002689 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002690 QualType ArgTy =
2691 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2692 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002693
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002694 if (Moving) {
2695 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2696 }
2697
John McCallf871d0c2010-08-07 06:22:56 +00002698 CXXCastPath BasePath;
2699 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002700 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2701 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002702 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002703 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002704
Anders Carlssone5ef7402010-04-23 03:10:23 +00002705 InitializationKind InitKind
2706 = InitializationKind::CreateDirect(Constructor->getLocation(),
2707 SourceLocation(), SourceLocation());
2708 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2709 &CopyCtorArg, 1);
2710 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002711 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002712 break;
2713 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002714 }
John McCall9ae2f072010-08-23 23:25:46 +00002715
Douglas Gregor53c374f2010-12-07 00:41:46 +00002716 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002717 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002718 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002719
Anders Carlssondefefd22010-04-23 02:00:02 +00002720 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002721 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002722 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2723 SourceLocation()),
2724 BaseSpec->isVirtual(),
2725 SourceLocation(),
2726 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002727 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002728 SourceLocation());
2729
Anders Carlssondefefd22010-04-23 02:00:02 +00002730 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002731}
2732
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002733static bool RefersToRValueRef(Expr *MemRef) {
2734 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2735 return Referenced->getType()->isRValueReferenceType();
2736}
2737
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002738static bool
2739BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002740 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002741 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002742 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002743 if (Field->isInvalidDecl())
2744 return true;
2745
Chandler Carruthf186b542010-06-29 23:50:44 +00002746 SourceLocation Loc = Constructor->getLocation();
2747
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002748 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2749 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002750 ParmVarDecl *Param = Constructor->getParamDecl(0);
2751 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002752
2753 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002754 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2755 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002756
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002757 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002758 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002759 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002760 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002761
Eli Friedman5f2987c2012-02-02 03:46:19 +00002762 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2763
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002764 if (Moving) {
2765 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2766 }
2767
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002768 // Build a reference to this field within the parameter.
2769 CXXScopeSpec SS;
2770 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2771 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002772 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2773 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002774 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002775 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002776 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002777 ParamType, Loc,
2778 /*IsArrow=*/false,
2779 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002780 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002781 /*FirstQualifierInScope=*/0,
2782 MemberLookup,
2783 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002784 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002785 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002786
2787 // C++11 [class.copy]p15:
2788 // - if a member m has rvalue reference type T&&, it is direct-initialized
2789 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002790 if (RefersToRValueRef(CtorArg.get())) {
2791 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002792 }
2793
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002794 // When the field we are copying is an array, create index variables for
2795 // each dimension of the array. We use these index variables to subscript
2796 // the source array, and other clients (e.g., CodeGen) will perform the
2797 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002798 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002799 QualType BaseType = Field->getType();
2800 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002801 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002802 while (const ConstantArrayType *Array
2803 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002804 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002805 // Create the iteration variable for this array index.
2806 IdentifierInfo *IterationVarName = 0;
2807 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002808 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002809 llvm::raw_svector_ostream OS(Str);
2810 OS << "__i" << IndexVariables.size();
2811 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2812 }
2813 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002814 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002815 IterationVarName, SizeType,
2816 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002817 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002818 IndexVariables.push_back(IterationVar);
2819
2820 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002821 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002822 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002823 assert(!IterationVarRef.isInvalid() &&
2824 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002825 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2826 assert(!IterationVarRef.isInvalid() &&
2827 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002828
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002829 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002830 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002831 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002832 Loc);
2833 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002834 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002835
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002836 BaseType = Array->getElementType();
2837 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002838
2839 // The array subscript expression is an lvalue, which is wrong for moving.
2840 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002842
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002843 // Construct the entity that we will be initializing. For an array, this
2844 // will be first element in the array, which may require several levels
2845 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002846 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002848 if (Indirect)
2849 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2850 else
2851 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002852 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2853 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2854 0,
2855 Entities.back()));
2856
2857 // Direct-initialize to use the copy constructor.
2858 InitializationKind InitKind =
2859 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2860
Sebastian Redl74e611a2011-09-04 18:14:28 +00002861 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002862 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002863 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002864
John McCall60d7b3a2010-08-24 06:29:42 +00002865 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002866 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002867 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002868 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002869 if (MemberInit.isInvalid())
2870 return true;
2871
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002872 if (Indirect) {
2873 assert(IndexVariables.size() == 0 &&
2874 "Indirect field improperly initialized");
2875 CXXMemberInit
2876 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2877 Loc, Loc,
2878 MemberInit.takeAs<Expr>(),
2879 Loc);
2880 } else
2881 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2882 Loc, MemberInit.takeAs<Expr>(),
2883 Loc,
2884 IndexVariables.data(),
2885 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002886 return false;
2887 }
2888
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002889 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2890
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002891 QualType FieldBaseElementType =
2892 SemaRef.Context.getBaseElementType(Field->getType());
2893
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002894 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002895 InitializedEntity InitEntity
2896 = Indirect? InitializedEntity::InitializeMember(Indirect)
2897 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002898 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002899 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002900
2901 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002902 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002903 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002904
Douglas Gregor53c374f2010-12-07 00:41:46 +00002905 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002906 if (MemberInit.isInvalid())
2907 return true;
2908
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002909 if (Indirect)
2910 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2911 Indirect, Loc,
2912 Loc,
2913 MemberInit.get(),
2914 Loc);
2915 else
2916 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2917 Field, Loc, Loc,
2918 MemberInit.get(),
2919 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002920 return false;
2921 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002922
Sean Hunt1f2f3842011-05-17 00:19:05 +00002923 if (!Field->getParent()->isUnion()) {
2924 if (FieldBaseElementType->isReferenceType()) {
2925 SemaRef.Diag(Constructor->getLocation(),
2926 diag::err_uninitialized_member_in_ctor)
2927 << (int)Constructor->isImplicit()
2928 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2929 << 0 << Field->getDeclName();
2930 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2931 return true;
2932 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002933
Sean Hunt1f2f3842011-05-17 00:19:05 +00002934 if (FieldBaseElementType.isConstQualified()) {
2935 SemaRef.Diag(Constructor->getLocation(),
2936 diag::err_uninitialized_member_in_ctor)
2937 << (int)Constructor->isImplicit()
2938 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2939 << 1 << Field->getDeclName();
2940 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2941 return true;
2942 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002943 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002944
David Blaikie4e4d0842012-03-11 07:00:24 +00002945 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002946 FieldBaseElementType->isObjCRetainableType() &&
2947 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2948 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002949 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002950 // Default-initialize Objective-C pointers to NULL.
2951 CXXMemberInit
2952 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2953 Loc, Loc,
2954 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2955 Loc);
2956 return false;
2957 }
2958
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002959 // Nothing to initialize.
2960 CXXMemberInit = 0;
2961 return false;
2962}
John McCallf1860e52010-05-20 23:23:51 +00002963
2964namespace {
2965struct BaseAndFieldInfo {
2966 Sema &S;
2967 CXXConstructorDecl *Ctor;
2968 bool AnyErrorsInInits;
2969 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002970 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002971 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002972
2973 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2974 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002975 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2976 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002977 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002978 else if (Generated && Ctor->isMoveConstructor())
2979 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002980 else
2981 IIK = IIK_Default;
2982 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002983
2984 bool isImplicitCopyOrMove() const {
2985 switch (IIK) {
2986 case IIK_Copy:
2987 case IIK_Move:
2988 return true;
2989
2990 case IIK_Default:
2991 return false;
2992 }
David Blaikie30263482012-01-20 21:50:17 +00002993
2994 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002995 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002996
2997 bool addFieldInitializer(CXXCtorInitializer *Init) {
2998 AllToInit.push_back(Init);
2999
3000 // Check whether this initializer makes the field "used".
3001 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3002 S.UnusedPrivateFields.remove(Init->getAnyMember());
3003
3004 return false;
3005 }
John McCallf1860e52010-05-20 23:23:51 +00003006};
3007}
3008
Richard Smitha4950662011-09-19 13:34:43 +00003009/// \brief Determine whether the given indirect field declaration is somewhere
3010/// within an anonymous union.
3011static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3012 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3013 CEnd = F->chain_end();
3014 C != CEnd; ++C)
3015 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3016 if (Record->isUnion())
3017 return true;
3018
3019 return false;
3020}
3021
Douglas Gregorddb21472011-11-02 23:04:16 +00003022/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3023/// array type.
3024static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3025 if (T->isIncompleteArrayType())
3026 return true;
3027
3028 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3029 if (!ArrayT->getSize())
3030 return true;
3031
3032 T = ArrayT->getElementType();
3033 }
3034
3035 return false;
3036}
3037
Richard Smith7a614d82011-06-11 17:19:42 +00003038static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003039 FieldDecl *Field,
3040 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003041
Chandler Carruthe861c602010-06-30 02:59:29 +00003042 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003043 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3044 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003045
Richard Smith0b8220a2012-08-07 21:30:42 +00003046 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003047 // has a brace-or-equal-initializer, the entity is initialized as specified
3048 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003049 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003050 CXXCtorInitializer *Init;
3051 if (Indirect)
3052 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3053 SourceLocation(),
3054 SourceLocation(), 0,
3055 SourceLocation());
3056 else
3057 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3058 SourceLocation(),
3059 SourceLocation(), 0,
3060 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003061 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003062 }
3063
Richard Smithc115f632011-09-18 11:14:50 +00003064 // Don't build an implicit initializer for union members if none was
3065 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003066 if (Field->getParent()->isUnion() ||
3067 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003068 return false;
3069
Douglas Gregorddb21472011-11-02 23:04:16 +00003070 // Don't initialize incomplete or zero-length arrays.
3071 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3072 return false;
3073
John McCallf1860e52010-05-20 23:23:51 +00003074 // Don't try to build an implicit initializer if there were semantic
3075 // errors in any of the initializers (and therefore we might be
3076 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003077 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003078 return false;
3079
Sean Huntcbb67482011-01-08 20:30:50 +00003080 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003081 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3082 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003083 return true;
John McCallf1860e52010-05-20 23:23:51 +00003084
Richard Smith0b8220a2012-08-07 21:30:42 +00003085 if (!Init)
3086 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003087
Richard Smith0b8220a2012-08-07 21:30:42 +00003088 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003089}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003090
3091bool
3092Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3093 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003094 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003095 Constructor->setNumCtorInitializers(1);
3096 CXXCtorInitializer **initializer =
3097 new (Context) CXXCtorInitializer*[1];
3098 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3099 Constructor->setCtorInitializers(initializer);
3100
Sean Huntb76af9c2011-05-03 23:05:34 +00003101 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003102 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003103 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3104 }
3105
Sean Huntc1598702011-05-05 00:05:47 +00003106 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003107
Sean Hunt059ce0d2011-05-01 07:04:31 +00003108 return false;
3109}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003110
David Blaikie93c86172013-01-17 05:26:25 +00003111bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3112 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003113 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003114 // Just store the initializers as written, they will be checked during
3115 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003116 if (!Initializers.empty()) {
3117 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003118 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003119 new (Context) CXXCtorInitializer*[Initializers.size()];
3120 memcpy(baseOrMemberInitializers, Initializers.data(),
3121 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003122 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003123 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003124
3125 // Let template instantiation know whether we had errors.
3126 if (AnyErrors)
3127 Constructor->setInvalidDecl();
3128
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003129 return false;
3130 }
3131
John McCallf1860e52010-05-20 23:23:51 +00003132 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003133
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003134 // We need to build the initializer AST according to order of construction
3135 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003136 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003137 if (!ClassDecl)
3138 return true;
3139
Eli Friedman80c30da2009-11-09 19:20:36 +00003140 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
David Blaikie93c86172013-01-17 05:26:25 +00003142 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003143 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003144
3145 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003146 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003147 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003148 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003149 }
3150
Anders Carlsson711f34a2010-04-21 19:52:01 +00003151 // Keep track of the direct virtual bases.
3152 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3153 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3154 E = ClassDecl->bases_end(); I != E; ++I) {
3155 if (I->isVirtual())
3156 DirectVBases.insert(I);
3157 }
3158
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003159 // Push virtual bases before others.
3160 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3161 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3162
Sean Huntcbb67482011-01-08 20:30:50 +00003163 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003164 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3165 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003166 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003167 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003168 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003169 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003170 VBase, IsInheritedVirtualBase,
3171 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003172 HadError = true;
3173 continue;
3174 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003175
John McCallf1860e52010-05-20 23:23:51 +00003176 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003177 }
3178 }
Mike Stump1eb44332009-09-09 15:08:12 +00003179
John McCallf1860e52010-05-20 23:23:51 +00003180 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003181 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3182 E = ClassDecl->bases_end(); Base != E; ++Base) {
3183 // Virtuals are in the virtual base list and already constructed.
3184 if (Base->isVirtual())
3185 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Sean Huntcbb67482011-01-08 20:30:50 +00003187 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003188 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3189 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003190 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003191 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003192 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003193 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003194 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003195 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003196 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003197 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003198
John McCallf1860e52010-05-20 23:23:51 +00003199 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003200 }
3201 }
Mike Stump1eb44332009-09-09 15:08:12 +00003202
John McCallf1860e52010-05-20 23:23:51 +00003203 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003204 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3205 MemEnd = ClassDecl->decls_end();
3206 Mem != MemEnd; ++Mem) {
3207 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003208 // C++ [class.bit]p2:
3209 // A declaration for a bit-field that omits the identifier declares an
3210 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3211 // initialized.
3212 if (F->isUnnamedBitfield())
3213 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003214
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003215 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003216 // handle anonymous struct/union fields based on their individual
3217 // indirect fields.
3218 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3219 continue;
3220
3221 if (CollectFieldInitializer(*this, Info, F))
3222 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003223 continue;
3224 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003225
3226 // Beyond this point, we only consider default initialization.
3227 if (Info.IIK != IIK_Default)
3228 continue;
3229
3230 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3231 if (F->getType()->isIncompleteArrayType()) {
3232 assert(ClassDecl->hasFlexibleArrayMember() &&
3233 "Incomplete array type is not valid");
3234 continue;
3235 }
3236
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003237 // Initialize each field of an anonymous struct individually.
3238 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3239 HadError = true;
3240
3241 continue;
3242 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003243 }
Mike Stump1eb44332009-09-09 15:08:12 +00003244
David Blaikie93c86172013-01-17 05:26:25 +00003245 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003246 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003247 Constructor->setNumCtorInitializers(NumInitializers);
3248 CXXCtorInitializer **baseOrMemberInitializers =
3249 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003250 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003251 NumInitializers * sizeof(CXXCtorInitializer*));
3252 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003253
John McCallef027fe2010-03-16 21:39:52 +00003254 // Constructors implicitly reference the base and member
3255 // destructors.
3256 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3257 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003258 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003259
3260 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003261}
3262
David Blaikieee000bb2013-01-17 08:49:22 +00003263static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003264 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003265 const RecordDecl *RD = RT->getDecl();
3266 if (RD->isAnonymousStructOrUnion()) {
3267 for (RecordDecl::field_iterator Field = RD->field_begin(),
3268 E = RD->field_end(); Field != E; ++Field)
3269 PopulateKeysForFields(*Field, IdealInits);
3270 return;
3271 }
Eli Friedman6347f422009-07-21 19:28:10 +00003272 }
David Blaikieee000bb2013-01-17 08:49:22 +00003273 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003274}
3275
Anders Carlssonea356fb2010-04-02 05:42:15 +00003276static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003277 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003278}
3279
Anders Carlssonea356fb2010-04-02 05:42:15 +00003280static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003281 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003282 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003283 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003284
David Blaikieee000bb2013-01-17 08:49:22 +00003285 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003286}
3287
David Blaikie93c86172013-01-17 05:26:25 +00003288static void DiagnoseBaseOrMemInitializerOrder(
3289 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3290 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003291 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003294 // Don't check initializers order unless the warning is enabled at the
3295 // location of at least one initializer.
3296 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003297 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003298 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003299 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3300 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003301 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003302 ShouldCheckOrder = true;
3303 break;
3304 }
3305 }
3306 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003307 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003308
John McCalld6ca8da2010-04-10 07:37:23 +00003309 // Build the list of bases and members in the order that they'll
3310 // actually be initialized. The explicit initializers should be in
3311 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003312 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Anders Carlsson071d6102010-04-02 03:38:04 +00003314 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3315
John McCalld6ca8da2010-04-10 07:37:23 +00003316 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003317 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003318 ClassDecl->vbases_begin(),
3319 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003320 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003321
John McCalld6ca8da2010-04-10 07:37:23 +00003322 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003323 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003324 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003325 if (Base->isVirtual())
3326 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003327 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003328 }
Mike Stump1eb44332009-09-09 15:08:12 +00003329
John McCalld6ca8da2010-04-10 07:37:23 +00003330 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003331 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003332 E = ClassDecl->field_end(); Field != E; ++Field) {
3333 if (Field->isUnnamedBitfield())
3334 continue;
3335
David Blaikieee000bb2013-01-17 08:49:22 +00003336 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003337 }
3338
John McCalld6ca8da2010-04-10 07:37:23 +00003339 unsigned NumIdealInits = IdealInitKeys.size();
3340 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003341
Sean Huntcbb67482011-01-08 20:30:50 +00003342 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003343 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003344 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003345 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003346
3347 // Scan forward to try to find this initializer in the idealized
3348 // initializers list.
3349 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3350 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003351 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003352
3353 // If we didn't find this initializer, it must be because we
3354 // scanned past it on a previous iteration. That can only
3355 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003356 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003357 Sema::SemaDiagnosticBuilder D =
3358 SemaRef.Diag(PrevInit->getSourceLocation(),
3359 diag::warn_initializer_out_of_order);
3360
Francois Pichet00eb3f92010-12-04 09:14:42 +00003361 if (PrevInit->isAnyMemberInitializer())
3362 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003363 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003364 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003365
Francois Pichet00eb3f92010-12-04 09:14:42 +00003366 if (Init->isAnyMemberInitializer())
3367 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003368 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003369 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003370
3371 // Move back to the initializer's location in the ideal list.
3372 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3373 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003374 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003375
3376 assert(IdealIndex != NumIdealInits &&
3377 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003378 }
John McCalld6ca8da2010-04-10 07:37:23 +00003379
3380 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003381 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003382}
3383
John McCall3c3ccdb2010-04-10 09:28:51 +00003384namespace {
3385bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003386 CXXCtorInitializer *Init,
3387 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003388 if (!PrevInit) {
3389 PrevInit = Init;
3390 return false;
3391 }
3392
3393 if (FieldDecl *Field = Init->getMember())
3394 S.Diag(Init->getSourceLocation(),
3395 diag::err_multiple_mem_initialization)
3396 << Field->getDeclName()
3397 << Init->getSourceRange();
3398 else {
John McCallf4c73712011-01-19 06:33:43 +00003399 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003400 assert(BaseClass && "neither field nor base");
3401 S.Diag(Init->getSourceLocation(),
3402 diag::err_multiple_base_initialization)
3403 << QualType(BaseClass, 0)
3404 << Init->getSourceRange();
3405 }
3406 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3407 << 0 << PrevInit->getSourceRange();
3408
3409 return true;
3410}
3411
Sean Huntcbb67482011-01-08 20:30:50 +00003412typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003413typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3414
3415bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003416 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003417 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003418 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003419 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003420 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003421
3422 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003423 if (Parent->isUnion()) {
3424 UnionEntry &En = Unions[Parent];
3425 if (En.first && En.first != Child) {
3426 S.Diag(Init->getSourceLocation(),
3427 diag::err_multiple_mem_union_initialization)
3428 << Field->getDeclName()
3429 << Init->getSourceRange();
3430 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3431 << 0 << En.second->getSourceRange();
3432 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003433 }
3434 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003435 En.first = Child;
3436 En.second = Init;
3437 }
David Blaikie6fe29652011-11-17 06:01:57 +00003438 if (!Parent->isAnonymousStructOrUnion())
3439 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003440 }
3441
3442 Child = Parent;
3443 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003444 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003445
3446 return false;
3447}
3448}
3449
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003450/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003451void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003452 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003453 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003454 bool AnyErrors) {
3455 if (!ConstructorDecl)
3456 return;
3457
3458 AdjustDeclIfTemplate(ConstructorDecl);
3459
3460 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003461 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003462
3463 if (!Constructor) {
3464 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3465 return;
3466 }
3467
John McCall3c3ccdb2010-04-10 09:28:51 +00003468 // Mapping for the duplicate initializers check.
3469 // For member initializers, this is keyed with a FieldDecl*.
3470 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003471 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003472
3473 // Mapping for the inconsistent anonymous-union initializers check.
3474 RedundantUnionMap MemberUnions;
3475
Anders Carlssonea356fb2010-04-02 05:42:15 +00003476 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003477 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003478 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003479
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003480 // Set the source order index.
3481 Init->setSourceOrder(i);
3482
Francois Pichet00eb3f92010-12-04 09:14:42 +00003483 if (Init->isAnyMemberInitializer()) {
3484 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003485 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3486 CheckRedundantUnionInit(*this, Init, MemberUnions))
3487 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003488 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003489 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3490 if (CheckRedundantInit(*this, Init, Members[Key]))
3491 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003492 } else {
3493 assert(Init->isDelegatingInitializer());
3494 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003495 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003496 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003497 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003498 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003499 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003500 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003501 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003502 // Return immediately as the initializer is set.
3503 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003504 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003505 }
3506
Anders Carlssonea356fb2010-04-02 05:42:15 +00003507 if (HadError)
3508 return;
3509
David Blaikie93c86172013-01-17 05:26:25 +00003510 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003511
David Blaikie93c86172013-01-17 05:26:25 +00003512 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003513}
3514
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003515void
John McCallef027fe2010-03-16 21:39:52 +00003516Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3517 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003518 // Ignore dependent contexts. Also ignore unions, since their members never
3519 // have destructors implicitly called.
3520 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003521 return;
John McCall58e6f342010-03-16 05:22:47 +00003522
3523 // FIXME: all the access-control diagnostics are positioned on the
3524 // field/base declaration. That's probably good; that said, the
3525 // user might reasonably want to know why the destructor is being
3526 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003527
Anders Carlsson9f853df2009-11-17 04:44:12 +00003528 // Non-static data members.
3529 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3530 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003531 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003532 if (Field->isInvalidDecl())
3533 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003534
3535 // Don't destroy incomplete or zero-length arrays.
3536 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3537 continue;
3538
Anders Carlsson9f853df2009-11-17 04:44:12 +00003539 QualType FieldType = Context.getBaseElementType(Field->getType());
3540
3541 const RecordType* RT = FieldType->getAs<RecordType>();
3542 if (!RT)
3543 continue;
3544
3545 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003546 if (FieldClassDecl->isInvalidDecl())
3547 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003548 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003549 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003550 // The destructor for an implicit anonymous union member is never invoked.
3551 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3552 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003553
Douglas Gregordb89f282010-07-01 22:47:18 +00003554 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003555 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003556 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003557 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003558 << Field->getDeclName()
3559 << FieldType);
3560
Eli Friedman5f2987c2012-02-02 03:46:19 +00003561 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003562 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003563 }
3564
John McCall58e6f342010-03-16 05:22:47 +00003565 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3566
Anders Carlsson9f853df2009-11-17 04:44:12 +00003567 // Bases.
3568 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3569 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003570 // Bases are always records in a well-formed non-dependent class.
3571 const RecordType *RT = Base->getType()->getAs<RecordType>();
3572
3573 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003574 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003575 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003576
John McCall58e6f342010-03-16 05:22:47 +00003577 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003578 // If our base class is invalid, we probably can't get its dtor anyway.
3579 if (BaseClassDecl->isInvalidDecl())
3580 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003581 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003582 continue;
John McCall58e6f342010-03-16 05:22:47 +00003583
Douglas Gregordb89f282010-07-01 22:47:18 +00003584 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003585 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003586
3587 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003588 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003589 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003590 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003591 << Base->getSourceRange(),
3592 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003593
Eli Friedman5f2987c2012-02-02 03:46:19 +00003594 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003595 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003596 }
3597
3598 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003599 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3600 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003601
3602 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003603 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003604
3605 // Ignore direct virtual bases.
3606 if (DirectVirtualBases.count(RT))
3607 continue;
3608
John McCall58e6f342010-03-16 05:22:47 +00003609 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003610 // If our base class is invalid, we probably can't get its dtor anyway.
3611 if (BaseClassDecl->isInvalidDecl())
3612 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003613 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003614 continue;
John McCall58e6f342010-03-16 05:22:47 +00003615
Douglas Gregordb89f282010-07-01 22:47:18 +00003616 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003617 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003618 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003619 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003620 << VBase->getType(),
3621 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003622
Eli Friedman5f2987c2012-02-02 03:46:19 +00003623 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003624 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003625 }
3626}
3627
John McCalld226f652010-08-21 09:40:31 +00003628void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003629 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003630 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003631
Mike Stump1eb44332009-09-09 15:08:12 +00003632 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003633 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003634 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003635}
3636
Mike Stump1eb44332009-09-09 15:08:12 +00003637bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003638 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003639 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3640 unsigned DiagID;
3641 AbstractDiagSelID SelID;
3642
3643 public:
3644 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3645 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3646
3647 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003648 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003649 if (SelID == -1)
3650 S.Diag(Loc, DiagID) << T;
3651 else
3652 S.Diag(Loc, DiagID) << SelID << T;
3653 }
3654 } Diagnoser(DiagID, SelID);
3655
3656 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003657}
3658
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003659bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003660 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003661 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003662 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Anders Carlsson11f21a02009-03-23 19:10:31 +00003664 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003665 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Ted Kremenek6217b802009-07-29 21:53:49 +00003667 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003668 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003669 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003670 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003672 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003673 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003674 }
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Ted Kremenek6217b802009-07-29 21:53:49 +00003676 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003677 if (!RT)
3678 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003679
John McCall86ff3082010-02-04 22:26:26 +00003680 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003681
John McCall94c3b562010-08-18 09:41:07 +00003682 // We can't answer whether something is abstract until it has a
3683 // definition. If it's currently being defined, we'll walk back
3684 // over all the declarations when we have a full definition.
3685 const CXXRecordDecl *Def = RD->getDefinition();
3686 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003687 return false;
3688
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003689 if (!RD->isAbstract())
3690 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003692 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003693 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003694
John McCall94c3b562010-08-18 09:41:07 +00003695 return true;
3696}
3697
3698void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3699 // Check if we've already emitted the list of pure virtual functions
3700 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003701 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003702 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003704 CXXFinalOverriderMap FinalOverriders;
3705 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003707 // Keep a set of seen pure methods so we won't diagnose the same method
3708 // more than once.
3709 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3710
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003711 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3712 MEnd = FinalOverriders.end();
3713 M != MEnd;
3714 ++M) {
3715 for (OverridingMethods::iterator SO = M->second.begin(),
3716 SOEnd = M->second.end();
3717 SO != SOEnd; ++SO) {
3718 // C++ [class.abstract]p4:
3719 // A class is abstract if it contains or inherits at least one
3720 // pure virtual function for which the final overrider is pure
3721 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003723 //
3724 if (SO->second.size() != 1)
3725 continue;
3726
3727 if (!SO->second.front().Method->isPure())
3728 continue;
3729
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003730 if (!SeenPureMethods.insert(SO->second.front().Method))
3731 continue;
3732
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003733 Diag(SO->second.front().Method->getLocation(),
3734 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003735 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003736 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003737 }
3738
3739 if (!PureVirtualClassDiagSet)
3740 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3741 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003742}
3743
Anders Carlsson8211eff2009-03-24 01:19:16 +00003744namespace {
John McCall94c3b562010-08-18 09:41:07 +00003745struct AbstractUsageInfo {
3746 Sema &S;
3747 CXXRecordDecl *Record;
3748 CanQualType AbstractType;
3749 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003750
John McCall94c3b562010-08-18 09:41:07 +00003751 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3752 : S(S), Record(Record),
3753 AbstractType(S.Context.getCanonicalType(
3754 S.Context.getTypeDeclType(Record))),
3755 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003756
John McCall94c3b562010-08-18 09:41:07 +00003757 void DiagnoseAbstractType() {
3758 if (Invalid) return;
3759 S.DiagnoseAbstractType(Record);
3760 Invalid = true;
3761 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003762
John McCall94c3b562010-08-18 09:41:07 +00003763 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3764};
3765
3766struct CheckAbstractUsage {
3767 AbstractUsageInfo &Info;
3768 const NamedDecl *Ctx;
3769
3770 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3771 : Info(Info), Ctx(Ctx) {}
3772
3773 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3774 switch (TL.getTypeLocClass()) {
3775#define ABSTRACT_TYPELOC(CLASS, PARENT)
3776#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003777 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003778#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003779 }
John McCall94c3b562010-08-18 09:41:07 +00003780 }
Mike Stump1eb44332009-09-09 15:08:12 +00003781
John McCall94c3b562010-08-18 09:41:07 +00003782 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3783 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3784 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003785 if (!TL.getArg(I))
3786 continue;
3787
John McCall94c3b562010-08-18 09:41:07 +00003788 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3789 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003790 }
John McCall94c3b562010-08-18 09:41:07 +00003791 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003792
John McCall94c3b562010-08-18 09:41:07 +00003793 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3794 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3795 }
Mike Stump1eb44332009-09-09 15:08:12 +00003796
John McCall94c3b562010-08-18 09:41:07 +00003797 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3798 // Visit the type parameters from a permissive context.
3799 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3800 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3801 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3802 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3803 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3804 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003805 }
John McCall94c3b562010-08-18 09:41:07 +00003806 }
Mike Stump1eb44332009-09-09 15:08:12 +00003807
John McCall94c3b562010-08-18 09:41:07 +00003808 // Visit pointee types from a permissive context.
3809#define CheckPolymorphic(Type) \
3810 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3811 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3812 }
3813 CheckPolymorphic(PointerTypeLoc)
3814 CheckPolymorphic(ReferenceTypeLoc)
3815 CheckPolymorphic(MemberPointerTypeLoc)
3816 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003817 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003818
John McCall94c3b562010-08-18 09:41:07 +00003819 /// Handle all the types we haven't given a more specific
3820 /// implementation for above.
3821 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3822 // Every other kind of type that we haven't called out already
3823 // that has an inner type is either (1) sugar or (2) contains that
3824 // inner type in some way as a subobject.
3825 if (TypeLoc Next = TL.getNextTypeLoc())
3826 return Visit(Next, Sel);
3827
3828 // If there's no inner type and we're in a permissive context,
3829 // don't diagnose.
3830 if (Sel == Sema::AbstractNone) return;
3831
3832 // Check whether the type matches the abstract type.
3833 QualType T = TL.getType();
3834 if (T->isArrayType()) {
3835 Sel = Sema::AbstractArrayType;
3836 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003837 }
John McCall94c3b562010-08-18 09:41:07 +00003838 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3839 if (CT != Info.AbstractType) return;
3840
3841 // It matched; do some magic.
3842 if (Sel == Sema::AbstractArrayType) {
3843 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3844 << T << TL.getSourceRange();
3845 } else {
3846 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3847 << Sel << T << TL.getSourceRange();
3848 }
3849 Info.DiagnoseAbstractType();
3850 }
3851};
3852
3853void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3854 Sema::AbstractDiagSelID Sel) {
3855 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3856}
3857
3858}
3859
3860/// Check for invalid uses of an abstract type in a method declaration.
3861static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3862 CXXMethodDecl *MD) {
3863 // No need to do the check on definitions, which require that
3864 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003865 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003866 return;
3867
3868 // For safety's sake, just ignore it if we don't have type source
3869 // information. This should never happen for non-implicit methods,
3870 // but...
3871 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3872 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3873}
3874
3875/// Check for invalid uses of an abstract type within a class definition.
3876static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3877 CXXRecordDecl *RD) {
3878 for (CXXRecordDecl::decl_iterator
3879 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3880 Decl *D = *I;
3881 if (D->isImplicit()) continue;
3882
3883 // Methods and method templates.
3884 if (isa<CXXMethodDecl>(D)) {
3885 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3886 } else if (isa<FunctionTemplateDecl>(D)) {
3887 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3888 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3889
3890 // Fields and static variables.
3891 } else if (isa<FieldDecl>(D)) {
3892 FieldDecl *FD = cast<FieldDecl>(D);
3893 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3894 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3895 } else if (isa<VarDecl>(D)) {
3896 VarDecl *VD = cast<VarDecl>(D);
3897 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3898 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3899
3900 // Nested classes and class templates.
3901 } else if (isa<CXXRecordDecl>(D)) {
3902 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3903 } else if (isa<ClassTemplateDecl>(D)) {
3904 CheckAbstractClassUsage(Info,
3905 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3906 }
3907 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003908}
3909
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003910/// \brief Perform semantic checks on a class definition that has been
3911/// completing, introducing implicitly-declared members, checking for
3912/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003913void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003914 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003915 return;
3916
John McCall94c3b562010-08-18 09:41:07 +00003917 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3918 AbstractUsageInfo Info(*this, Record);
3919 CheckAbstractClassUsage(Info, Record);
3920 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003921
3922 // If this is not an aggregate type and has no user-declared constructor,
3923 // complain about any non-static data members of reference or const scalar
3924 // type, since they will never get initializers.
3925 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003926 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3927 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003928 bool Complained = false;
3929 for (RecordDecl::field_iterator F = Record->field_begin(),
3930 FEnd = Record->field_end();
3931 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003932 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003933 continue;
3934
Douglas Gregor325e5932010-04-15 00:00:53 +00003935 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003936 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003937 if (!Complained) {
3938 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3939 << Record->getTagKind() << Record;
3940 Complained = true;
3941 }
3942
3943 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3944 << F->getType()->isReferenceType()
3945 << F->getDeclName();
3946 }
3947 }
3948 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003949
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003950 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003951 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003952
3953 if (Record->getIdentifier()) {
3954 // C++ [class.mem]p13:
3955 // If T is the name of a class, then each of the following shall have a
3956 // name different from T:
3957 // - every member of every anonymous union that is a member of class T.
3958 //
3959 // C++ [class.mem]p14:
3960 // In addition, if class T has a user-declared constructor (12.1), every
3961 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003962 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3963 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3964 ++I) {
3965 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003966 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3967 isa<IndirectFieldDecl>(D)) {
3968 Diag(D->getLocation(), diag::err_member_name_of_class)
3969 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003970 break;
3971 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003972 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003973 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003974
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003975 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003976 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003977 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003978 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003979 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3980 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3981 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003982
David Blaikieb6b5b972012-09-21 03:21:07 +00003983 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3984 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3985 DiagnoseAbstractType(Record);
3986 }
3987
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003988 if (!Record->isDependentType()) {
3989 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3990 MEnd = Record->method_end();
3991 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00003992 // See if a method overloads virtual methods in a base
3993 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00003994 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003995 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00003996
3997 // Check whether the explicitly-defaulted special members are valid.
3998 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3999 CheckExplicitlyDefaultedSpecialMember(*M);
4000
4001 // For an explicitly defaulted or deleted special member, we defer
4002 // determining triviality until the class is complete. That time is now!
4003 if (!M->isImplicit() && !M->isUserProvided()) {
4004 CXXSpecialMember CSM = getSpecialMember(*M);
4005 if (CSM != CXXInvalid) {
4006 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4007
4008 // Inform the class that we've finished declaring this member.
4009 Record->finishedDefaultedOrDeletedMember(*M);
4010 }
4011 }
4012 }
4013 }
4014
4015 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4016 // function that is not a constructor declares that member function to be
4017 // const. [...] The class of which that function is a member shall be
4018 // a literal type.
4019 //
4020 // If the class has virtual bases, any constexpr members will already have
4021 // been diagnosed by the checks performed on the member declaration, so
4022 // suppress this (less useful) diagnostic.
4023 //
4024 // We delay this until we know whether an explicitly-defaulted (or deleted)
4025 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004026 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004027 !Record->isLiteral() && !Record->getNumVBases()) {
4028 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4029 MEnd = Record->method_end();
4030 M != MEnd; ++M) {
4031 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4032 switch (Record->getTemplateSpecializationKind()) {
4033 case TSK_ImplicitInstantiation:
4034 case TSK_ExplicitInstantiationDeclaration:
4035 case TSK_ExplicitInstantiationDefinition:
4036 // If a template instantiates to a non-literal type, but its members
4037 // instantiate to constexpr functions, the template is technically
4038 // ill-formed, but we allow it for sanity.
4039 continue;
4040
4041 case TSK_Undeclared:
4042 case TSK_ExplicitSpecialization:
4043 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4044 diag::err_constexpr_method_non_literal);
4045 break;
4046 }
4047
4048 // Only produce one error per class.
4049 break;
4050 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004051 }
4052 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004053
4054 // Declare inherited constructors. We do this eagerly here because:
4055 // - The standard requires an eager diagnostic for conflicting inherited
4056 // constructors from different classes.
4057 // - The lazy declaration of the other implicit constructors is so as to not
4058 // waste space and performance on classes that are not meant to be
4059 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4060 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004061 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004062}
4063
Richard Smith7756afa2012-06-10 05:43:50 +00004064/// Is the special member function which would be selected to perform the
4065/// specified operation on the specified class type a constexpr constructor?
4066static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4067 Sema::CXXSpecialMember CSM,
4068 bool ConstArg) {
4069 Sema::SpecialMemberOverloadResult *SMOR =
4070 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4071 false, false, false, false);
4072 if (!SMOR || !SMOR->getMethod())
4073 // A constructor we wouldn't select can't be "involved in initializing"
4074 // anything.
4075 return true;
4076 return SMOR->getMethod()->isConstexpr();
4077}
4078
4079/// Determine whether the specified special member function would be constexpr
4080/// if it were implicitly defined.
4081static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4082 Sema::CXXSpecialMember CSM,
4083 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004084 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004085 return false;
4086
4087 // C++11 [dcl.constexpr]p4:
4088 // In the definition of a constexpr constructor [...]
4089 switch (CSM) {
4090 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004091 // Since default constructor lookup is essentially trivial (and cannot
4092 // involve, for instance, template instantiation), we compute whether a
4093 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4094 //
4095 // This is important for performance; we need to know whether the default
4096 // constructor is constexpr to determine whether the type is a literal type.
4097 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4098
Richard Smith7756afa2012-06-10 05:43:50 +00004099 case Sema::CXXCopyConstructor:
4100 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004101 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004102 break;
4103
4104 case Sema::CXXCopyAssignment:
4105 case Sema::CXXMoveAssignment:
4106 case Sema::CXXDestructor:
4107 case Sema::CXXInvalid:
4108 return false;
4109 }
4110
4111 // -- if the class is a non-empty union, or for each non-empty anonymous
4112 // union member of a non-union class, exactly one non-static data member
4113 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004114 //
4115 // If we squint, this is guaranteed, since exactly one non-static data member
4116 // will be initialized (if the constructor isn't deleted), we just don't know
4117 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004118 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004119 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004120
4121 // -- the class shall not have any virtual base classes;
4122 if (ClassDecl->getNumVBases())
4123 return false;
4124
4125 // -- every constructor involved in initializing [...] base class
4126 // sub-objects shall be a constexpr constructor;
4127 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4128 BEnd = ClassDecl->bases_end();
4129 B != BEnd; ++B) {
4130 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4131 if (!BaseType) continue;
4132
4133 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4134 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4135 return false;
4136 }
4137
4138 // -- every constructor involved in initializing non-static data members
4139 // [...] shall be a constexpr constructor;
4140 // -- every non-static data member and base class sub-object shall be
4141 // initialized
4142 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4143 FEnd = ClassDecl->field_end();
4144 F != FEnd; ++F) {
4145 if (F->isInvalidDecl())
4146 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004147 if (const RecordType *RecordTy =
4148 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004149 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4150 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4151 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004152 }
4153 }
4154
4155 // All OK, it's constexpr!
4156 return true;
4157}
4158
Richard Smithb9d0b762012-07-27 04:22:15 +00004159static Sema::ImplicitExceptionSpecification
4160computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4161 switch (S.getSpecialMember(MD)) {
4162 case Sema::CXXDefaultConstructor:
4163 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4164 case Sema::CXXCopyConstructor:
4165 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4166 case Sema::CXXCopyAssignment:
4167 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4168 case Sema::CXXMoveConstructor:
4169 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4170 case Sema::CXXMoveAssignment:
4171 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4172 case Sema::CXXDestructor:
4173 return S.ComputeDefaultedDtorExceptionSpec(MD);
4174 case Sema::CXXInvalid:
4175 break;
4176 }
4177 llvm_unreachable("only special members have implicit exception specs");
4178}
4179
Richard Smithdd25e802012-07-30 23:48:14 +00004180static void
4181updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4182 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4183 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4184 ExceptSpec.getEPI(EPI);
4185 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4186 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4187 FPT->getNumArgs(), EPI));
4188 FD->setType(QualType(NewFPT, 0));
4189}
4190
Richard Smithb9d0b762012-07-27 04:22:15 +00004191void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4192 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4193 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4194 return;
4195
Richard Smithdd25e802012-07-30 23:48:14 +00004196 // Evaluate the exception specification.
4197 ImplicitExceptionSpecification ExceptSpec =
4198 computeImplicitExceptionSpec(*this, Loc, MD);
4199
4200 // Update the type of the special member to use it.
4201 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4202
4203 // A user-provided destructor can be defined outside the class. When that
4204 // happens, be sure to update the exception specification on both
4205 // declarations.
4206 const FunctionProtoType *CanonicalFPT =
4207 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4208 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4209 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4210 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004211}
4212
Richard Smith3003e1d2012-05-15 04:39:51 +00004213void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4214 CXXRecordDecl *RD = MD->getParent();
4215 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004216
Richard Smith3003e1d2012-05-15 04:39:51 +00004217 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4218 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004219
4220 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004221 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004222 bool First = MD == MD->getCanonicalDecl();
4223
4224 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004225
4226 // C++11 [dcl.fct.def.default]p1:
4227 // A function that is explicitly defaulted shall
4228 // -- be a special member function (checked elsewhere),
4229 // -- have the same type (except for ref-qualifiers, and except that a
4230 // copy operation can take a non-const reference) as an implicit
4231 // declaration, and
4232 // -- not have default arguments.
4233 unsigned ExpectedParams = 1;
4234 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4235 ExpectedParams = 0;
4236 if (MD->getNumParams() != ExpectedParams) {
4237 // This also checks for default arguments: a copy or move constructor with a
4238 // default argument is classified as a default constructor, and assignment
4239 // operations and destructors can't have default arguments.
4240 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4241 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004242 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004243 } else if (MD->isVariadic()) {
4244 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4245 << CSM << MD->getSourceRange();
4246 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004247 }
4248
Richard Smith3003e1d2012-05-15 04:39:51 +00004249 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004250
Richard Smith7756afa2012-06-10 05:43:50 +00004251 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004252 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004253 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004254 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004255 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004256
Richard Smith3003e1d2012-05-15 04:39:51 +00004257 QualType ReturnType = Context.VoidTy;
4258 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4259 // Check for return type matching.
4260 ReturnType = Type->getResultType();
4261 QualType ExpectedReturnType =
4262 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4263 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4264 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4265 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4266 HadError = true;
4267 }
4268
4269 // A defaulted special member cannot have cv-qualifiers.
4270 if (Type->getTypeQuals()) {
4271 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4272 << (CSM == CXXMoveAssignment);
4273 HadError = true;
4274 }
4275 }
4276
4277 // Check for parameter type matching.
4278 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004279 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004280 if (ExpectedParams && ArgType->isReferenceType()) {
4281 // Argument must be reference to possibly-const T.
4282 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004283 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004284
4285 if (ReferentType.isVolatileQualified()) {
4286 Diag(MD->getLocation(),
4287 diag::err_defaulted_special_member_volatile_param) << CSM;
4288 HadError = true;
4289 }
4290
Richard Smith7756afa2012-06-10 05:43:50 +00004291 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004292 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4293 Diag(MD->getLocation(),
4294 diag::err_defaulted_special_member_copy_const_param)
4295 << (CSM == CXXCopyAssignment);
4296 // FIXME: Explain why this special member can't be const.
4297 } else {
4298 Diag(MD->getLocation(),
4299 diag::err_defaulted_special_member_move_const_param)
4300 << (CSM == CXXMoveAssignment);
4301 }
4302 HadError = true;
4303 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004304 } else if (ExpectedParams) {
4305 // A copy assignment operator can take its argument by value, but a
4306 // defaulted one cannot.
4307 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004308 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004309 HadError = true;
4310 }
Sean Huntbe631222011-05-17 20:44:43 +00004311
Richard Smith61802452011-12-22 02:22:31 +00004312 // C++11 [dcl.fct.def.default]p2:
4313 // An explicitly-defaulted function may be declared constexpr only if it
4314 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004315 // Do not apply this rule to members of class templates, since core issue 1358
4316 // makes such functions always instantiate to constexpr functions. For
4317 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004318 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4319 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004320 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4321 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4322 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004323 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004324 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004325 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004326
Richard Smith61802452011-12-22 02:22:31 +00004327 // and may have an explicit exception-specification only if it is compatible
4328 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004329 if (Type->hasExceptionSpec()) {
4330 // Delay the check if this is the first declaration of the special member,
4331 // since we may not have parsed some necessary in-class initializers yet.
4332 if (First)
4333 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4334 else
4335 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4336 }
Richard Smith61802452011-12-22 02:22:31 +00004337
4338 // If a function is explicitly defaulted on its first declaration,
4339 if (First) {
4340 // -- it is implicitly considered to be constexpr if the implicit
4341 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004342 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004343
Richard Smith3003e1d2012-05-15 04:39:51 +00004344 // -- it is implicitly considered to have the same exception-specification
4345 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004346 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4347 EPI.ExceptionSpecType = EST_Unevaluated;
4348 EPI.ExceptionSpecDecl = MD;
4349 MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4350 ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004351 }
4352
Richard Smith3003e1d2012-05-15 04:39:51 +00004353 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004354 if (First) {
4355 MD->setDeletedAsWritten();
4356 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004357 // C++11 [dcl.fct.def.default]p4:
4358 // [For a] user-provided explicitly-defaulted function [...] if such a
4359 // function is implicitly defined as deleted, the program is ill-formed.
4360 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4361 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004362 }
4363 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004364
Richard Smith3003e1d2012-05-15 04:39:51 +00004365 if (HadError)
4366 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004367}
4368
Richard Smith1d28caf2012-12-11 01:14:52 +00004369/// Check whether the exception specification provided for an
4370/// explicitly-defaulted special member matches the exception specification
4371/// that would have been generated for an implicit special member, per
4372/// C++11 [dcl.fct.def.default]p2.
4373void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4374 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4375 // Compute the implicit exception specification.
4376 FunctionProtoType::ExtProtoInfo EPI;
4377 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4378 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4379 Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4380
4381 // Ensure that it matches.
4382 CheckEquivalentExceptionSpec(
4383 PDiag(diag::err_incorrect_defaulted_exception_spec)
4384 << getSpecialMember(MD), PDiag(),
4385 ImplicitType, SourceLocation(),
4386 SpecifiedType, MD->getLocation());
4387}
4388
4389void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4390 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4391 I != N; ++I)
4392 CheckExplicitlyDefaultedMemberExceptionSpec(
4393 DelayedDefaultedMemberExceptionSpecs[I].first,
4394 DelayedDefaultedMemberExceptionSpecs[I].second);
4395
4396 DelayedDefaultedMemberExceptionSpecs.clear();
4397}
4398
Richard Smith7d5088a2012-02-18 02:02:13 +00004399namespace {
4400struct SpecialMemberDeletionInfo {
4401 Sema &S;
4402 CXXMethodDecl *MD;
4403 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004404 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004405
4406 // Properties of the special member, computed for convenience.
4407 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4408 SourceLocation Loc;
4409
4410 bool AllFieldsAreConst;
4411
4412 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004413 Sema::CXXSpecialMember CSM, bool Diagnose)
4414 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004415 IsConstructor(false), IsAssignment(false), IsMove(false),
4416 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4417 AllFieldsAreConst(true) {
4418 switch (CSM) {
4419 case Sema::CXXDefaultConstructor:
4420 case Sema::CXXCopyConstructor:
4421 IsConstructor = true;
4422 break;
4423 case Sema::CXXMoveConstructor:
4424 IsConstructor = true;
4425 IsMove = true;
4426 break;
4427 case Sema::CXXCopyAssignment:
4428 IsAssignment = true;
4429 break;
4430 case Sema::CXXMoveAssignment:
4431 IsAssignment = true;
4432 IsMove = true;
4433 break;
4434 case Sema::CXXDestructor:
4435 break;
4436 case Sema::CXXInvalid:
4437 llvm_unreachable("invalid special member kind");
4438 }
4439
4440 if (MD->getNumParams()) {
4441 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4442 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4443 }
4444 }
4445
4446 bool inUnion() const { return MD->getParent()->isUnion(); }
4447
4448 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004449 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4450 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004451 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004452 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4453 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4454 Quals = 0;
4455 return S.LookupSpecialMember(Class, CSM,
4456 ConstArg || (Quals & Qualifiers::Const),
4457 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004458 MD->getRefQualifier() == RQ_RValue,
4459 TQ & Qualifiers::Const,
4460 TQ & Qualifiers::Volatile);
4461 }
4462
Richard Smith6c4c36c2012-03-30 20:53:28 +00004463 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004464
Richard Smith6c4c36c2012-03-30 20:53:28 +00004465 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004466 bool shouldDeleteForField(FieldDecl *FD);
4467 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004468
Richard Smith517bb842012-07-18 03:51:16 +00004469 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4470 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004471 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4472 Sema::SpecialMemberOverloadResult *SMOR,
4473 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004474
4475 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004476};
4477}
4478
John McCall12d8d802012-04-09 20:53:23 +00004479/// Is the given special member inaccessible when used on the given
4480/// sub-object.
4481bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4482 CXXMethodDecl *target) {
4483 /// If we're operating on a base class, the object type is the
4484 /// type of this special member.
4485 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004486 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004487 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4488 objectTy = S.Context.getTypeDeclType(MD->getParent());
4489 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4490
4491 // If we're operating on a field, the object type is the type of the field.
4492 } else {
4493 objectTy = S.Context.getTypeDeclType(target->getParent());
4494 }
4495
4496 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4497}
4498
Richard Smith6c4c36c2012-03-30 20:53:28 +00004499/// Check whether we should delete a special member due to the implicit
4500/// definition containing a call to a special member of a subobject.
4501bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4502 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4503 bool IsDtorCallInCtor) {
4504 CXXMethodDecl *Decl = SMOR->getMethod();
4505 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4506
4507 int DiagKind = -1;
4508
4509 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4510 DiagKind = !Decl ? 0 : 1;
4511 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4512 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004513 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004514 DiagKind = 3;
4515 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4516 !Decl->isTrivial()) {
4517 // A member of a union must have a trivial corresponding special member.
4518 // As a weird special case, a destructor call from a union's constructor
4519 // must be accessible and non-deleted, but need not be trivial. Such a
4520 // destructor is never actually called, but is semantically checked as
4521 // if it were.
4522 DiagKind = 4;
4523 }
4524
4525 if (DiagKind == -1)
4526 return false;
4527
4528 if (Diagnose) {
4529 if (Field) {
4530 S.Diag(Field->getLocation(),
4531 diag::note_deleted_special_member_class_subobject)
4532 << CSM << MD->getParent() << /*IsField*/true
4533 << Field << DiagKind << IsDtorCallInCtor;
4534 } else {
4535 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4536 S.Diag(Base->getLocStart(),
4537 diag::note_deleted_special_member_class_subobject)
4538 << CSM << MD->getParent() << /*IsField*/false
4539 << Base->getType() << DiagKind << IsDtorCallInCtor;
4540 }
4541
4542 if (DiagKind == 1)
4543 S.NoteDeletedFunction(Decl);
4544 // FIXME: Explain inaccessibility if DiagKind == 3.
4545 }
4546
4547 return true;
4548}
4549
Richard Smith9a561d52012-02-26 09:11:52 +00004550/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004551/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004552bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004553 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004554 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004555
4556 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004557 // -- any direct or virtual base class, or non-static data member with no
4558 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004559 // either M has no default constructor or overload resolution as applied
4560 // to M's default constructor results in an ambiguity or in a function
4561 // that is deleted or inaccessible
4562 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4563 // -- a direct or virtual base class B that cannot be copied/moved because
4564 // overload resolution, as applied to B's corresponding special member,
4565 // results in an ambiguity or a function that is deleted or inaccessible
4566 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004567 // C++11 [class.dtor]p5:
4568 // -- any direct or virtual base class [...] has a type with a destructor
4569 // that is deleted or inaccessible
4570 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004571 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004572 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004573 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004574
Richard Smith6c4c36c2012-03-30 20:53:28 +00004575 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4576 // -- any direct or virtual base class or non-static data member has a
4577 // type with a destructor that is deleted or inaccessible
4578 if (IsConstructor) {
4579 Sema::SpecialMemberOverloadResult *SMOR =
4580 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4581 false, false, false, false, false);
4582 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4583 return true;
4584 }
4585
Richard Smith9a561d52012-02-26 09:11:52 +00004586 return false;
4587}
4588
4589/// Check whether we should delete a special member function due to the class
4590/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004591bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004592 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004593 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004594}
4595
4596/// Check whether we should delete a special member function due to the class
4597/// having a particular non-static data member.
4598bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4599 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4600 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4601
4602 if (CSM == Sema::CXXDefaultConstructor) {
4603 // For a default constructor, all references must be initialized in-class
4604 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004605 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4606 if (Diagnose)
4607 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4608 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004609 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004610 }
Richard Smith79363f52012-02-27 06:07:25 +00004611 // C++11 [class.ctor]p5: any non-variant non-static data member of
4612 // const-qualified type (or array thereof) with no
4613 // brace-or-equal-initializer does not have a user-provided default
4614 // constructor.
4615 if (!inUnion() && FieldType.isConstQualified() &&
4616 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004617 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4618 if (Diagnose)
4619 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004620 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004621 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004622 }
4623
4624 if (inUnion() && !FieldType.isConstQualified())
4625 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004626 } else if (CSM == Sema::CXXCopyConstructor) {
4627 // For a copy constructor, data members must not be of rvalue reference
4628 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004629 if (FieldType->isRValueReferenceType()) {
4630 if (Diagnose)
4631 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4632 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004633 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004634 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004635 } else if (IsAssignment) {
4636 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004637 if (FieldType->isReferenceType()) {
4638 if (Diagnose)
4639 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4640 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004641 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004642 }
4643 if (!FieldRecord && FieldType.isConstQualified()) {
4644 // C++11 [class.copy]p23:
4645 // -- a non-static data member of const non-class type (or array thereof)
4646 if (Diagnose)
4647 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004648 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004649 return true;
4650 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004651 }
4652
4653 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004654 // Some additional restrictions exist on the variant members.
4655 if (!inUnion() && FieldRecord->isUnion() &&
4656 FieldRecord->isAnonymousStructOrUnion()) {
4657 bool AllVariantFieldsAreConst = true;
4658
Richard Smithdf8dc862012-03-29 19:00:10 +00004659 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004660 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4661 UE = FieldRecord->field_end();
4662 UI != UE; ++UI) {
4663 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004664
4665 if (!UnionFieldType.isConstQualified())
4666 AllVariantFieldsAreConst = false;
4667
Richard Smith9a561d52012-02-26 09:11:52 +00004668 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4669 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004670 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4671 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004672 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004673 }
4674
4675 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004676 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004677 FieldRecord->field_begin() != FieldRecord->field_end()) {
4678 if (Diagnose)
4679 S.Diag(FieldRecord->getLocation(),
4680 diag::note_deleted_default_ctor_all_const)
4681 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004682 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004683 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004684
Richard Smithdf8dc862012-03-29 19:00:10 +00004685 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004686 // This is technically non-conformant, but sanity demands it.
4687 return false;
4688 }
4689
Richard Smith517bb842012-07-18 03:51:16 +00004690 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4691 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004692 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004693 }
4694
4695 return false;
4696}
4697
4698/// C++11 [class.ctor] p5:
4699/// A defaulted default constructor for a class X is defined as deleted if
4700/// X is a union and all of its variant members are of const-qualified type.
4701bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004702 // This is a silly definition, because it gives an empty union a deleted
4703 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004704 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4705 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4706 if (Diagnose)
4707 S.Diag(MD->getParent()->getLocation(),
4708 diag::note_deleted_default_ctor_all_const)
4709 << MD->getParent() << /*not anonymous union*/0;
4710 return true;
4711 }
4712 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004713}
4714
4715/// Determine whether a defaulted special member function should be defined as
4716/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4717/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004718bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4719 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004720 if (MD->isInvalidDecl())
4721 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004722 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004723 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004724 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004725 return false;
4726
Richard Smith7d5088a2012-02-18 02:02:13 +00004727 // C++11 [expr.lambda.prim]p19:
4728 // The closure type associated with a lambda-expression has a
4729 // deleted (8.4.3) default constructor and a deleted copy
4730 // assignment operator.
4731 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4733 if (Diagnose)
4734 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004735 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004736 }
4737
Richard Smith5bdaac52012-04-02 20:59:25 +00004738 // For an anonymous struct or union, the copy and assignment special members
4739 // will never be used, so skip the check. For an anonymous union declared at
4740 // namespace scope, the constructor and destructor are used.
4741 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4742 RD->isAnonymousStructOrUnion())
4743 return false;
4744
Richard Smith6c4c36c2012-03-30 20:53:28 +00004745 // C++11 [class.copy]p7, p18:
4746 // If the class definition declares a move constructor or move assignment
4747 // operator, an implicitly declared copy constructor or copy assignment
4748 // operator is defined as deleted.
4749 if (MD->isImplicit() &&
4750 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4751 CXXMethodDecl *UserDeclaredMove = 0;
4752
4753 // In Microsoft mode, a user-declared move only causes the deletion of the
4754 // corresponding copy operation, not both copy operations.
4755 if (RD->hasUserDeclaredMoveConstructor() &&
4756 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4757 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004758
4759 // Find any user-declared move constructor.
4760 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4761 E = RD->ctor_end(); I != E; ++I) {
4762 if (I->isMoveConstructor()) {
4763 UserDeclaredMove = *I;
4764 break;
4765 }
4766 }
Richard Smith1c931be2012-04-02 18:40:40 +00004767 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004768 } else if (RD->hasUserDeclaredMoveAssignment() &&
4769 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4770 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004771
4772 // Find any user-declared move assignment operator.
4773 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4774 E = RD->method_end(); I != E; ++I) {
4775 if (I->isMoveAssignmentOperator()) {
4776 UserDeclaredMove = *I;
4777 break;
4778 }
4779 }
Richard Smith1c931be2012-04-02 18:40:40 +00004780 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004781 }
4782
4783 if (UserDeclaredMove) {
4784 Diag(UserDeclaredMove->getLocation(),
4785 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004786 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004787 << UserDeclaredMove->isMoveAssignmentOperator();
4788 return true;
4789 }
4790 }
Sean Hunte16da072011-10-10 06:18:57 +00004791
Richard Smith5bdaac52012-04-02 20:59:25 +00004792 // Do access control from the special member function
4793 ContextRAII MethodContext(*this, MD);
4794
Richard Smith9a561d52012-02-26 09:11:52 +00004795 // C++11 [class.dtor]p5:
4796 // -- for a virtual destructor, lookup of the non-array deallocation function
4797 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004798 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004799 FunctionDecl *OperatorDelete = 0;
4800 DeclarationName Name =
4801 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4802 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004803 OperatorDelete, false)) {
4804 if (Diagnose)
4805 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004806 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004807 }
Richard Smith9a561d52012-02-26 09:11:52 +00004808 }
4809
Richard Smith6c4c36c2012-03-30 20:53:28 +00004810 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004811
Sean Huntcdee3fe2011-05-11 22:34:38 +00004812 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004813 BE = RD->bases_end(); BI != BE; ++BI)
4814 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004815 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004816 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004817
4818 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004819 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004820 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004821 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004822
4823 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004824 FE = RD->field_end(); FI != FE; ++FI)
4825 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004826 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004827 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004828
Richard Smith7d5088a2012-02-18 02:02:13 +00004829 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004830 return true;
4831
4832 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004833}
4834
Richard Smithac713512012-12-08 02:53:02 +00004835/// Perform lookup for a special member of the specified kind, and determine
4836/// whether it is trivial. If the triviality can be determined without the
4837/// lookup, skip it. This is intended for use when determining whether a
4838/// special member of a containing object is trivial, and thus does not ever
4839/// perform overload resolution for default constructors.
4840///
4841/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4842/// member that was most likely to be intended to be trivial, if any.
4843static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4844 Sema::CXXSpecialMember CSM, unsigned Quals,
4845 CXXMethodDecl **Selected) {
4846 if (Selected)
4847 *Selected = 0;
4848
4849 switch (CSM) {
4850 case Sema::CXXInvalid:
4851 llvm_unreachable("not a special member");
4852
4853 case Sema::CXXDefaultConstructor:
4854 // C++11 [class.ctor]p5:
4855 // A default constructor is trivial if:
4856 // - all the [direct subobjects] have trivial default constructors
4857 //
4858 // Note, no overload resolution is performed in this case.
4859 if (RD->hasTrivialDefaultConstructor())
4860 return true;
4861
4862 if (Selected) {
4863 // If there's a default constructor which could have been trivial, dig it
4864 // out. Otherwise, if there's any user-provided default constructor, point
4865 // to that as an example of why there's not a trivial one.
4866 CXXConstructorDecl *DefCtor = 0;
4867 if (RD->needsImplicitDefaultConstructor())
4868 S.DeclareImplicitDefaultConstructor(RD);
4869 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4870 CE = RD->ctor_end(); CI != CE; ++CI) {
4871 if (!CI->isDefaultConstructor())
4872 continue;
4873 DefCtor = *CI;
4874 if (!DefCtor->isUserProvided())
4875 break;
4876 }
4877
4878 *Selected = DefCtor;
4879 }
4880
4881 return false;
4882
4883 case Sema::CXXDestructor:
4884 // C++11 [class.dtor]p5:
4885 // A destructor is trivial if:
4886 // - all the direct [subobjects] have trivial destructors
4887 if (RD->hasTrivialDestructor())
4888 return true;
4889
4890 if (Selected) {
4891 if (RD->needsImplicitDestructor())
4892 S.DeclareImplicitDestructor(RD);
4893 *Selected = RD->getDestructor();
4894 }
4895
4896 return false;
4897
4898 case Sema::CXXCopyConstructor:
4899 // C++11 [class.copy]p12:
4900 // A copy constructor is trivial if:
4901 // - the constructor selected to copy each direct [subobject] is trivial
4902 if (RD->hasTrivialCopyConstructor()) {
4903 if (Quals == Qualifiers::Const)
4904 // We must either select the trivial copy constructor or reach an
4905 // ambiguity; no need to actually perform overload resolution.
4906 return true;
4907 } else if (!Selected) {
4908 return false;
4909 }
4910 // In C++98, we are not supposed to perform overload resolution here, but we
4911 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4912 // cases like B as having a non-trivial copy constructor:
4913 // struct A { template<typename T> A(T&); };
4914 // struct B { mutable A a; };
4915 goto NeedOverloadResolution;
4916
4917 case Sema::CXXCopyAssignment:
4918 // C++11 [class.copy]p25:
4919 // A copy assignment operator is trivial if:
4920 // - the assignment operator selected to copy each direct [subobject] is
4921 // trivial
4922 if (RD->hasTrivialCopyAssignment()) {
4923 if (Quals == Qualifiers::Const)
4924 return true;
4925 } else if (!Selected) {
4926 return false;
4927 }
4928 // In C++98, we are not supposed to perform overload resolution here, but we
4929 // treat that as a language defect.
4930 goto NeedOverloadResolution;
4931
4932 case Sema::CXXMoveConstructor:
4933 case Sema::CXXMoveAssignment:
4934 NeedOverloadResolution:
4935 Sema::SpecialMemberOverloadResult *SMOR =
4936 S.LookupSpecialMember(RD, CSM,
4937 Quals & Qualifiers::Const,
4938 Quals & Qualifiers::Volatile,
4939 /*RValueThis*/false, /*ConstThis*/false,
4940 /*VolatileThis*/false);
4941
4942 // The standard doesn't describe how to behave if the lookup is ambiguous.
4943 // We treat it as not making the member non-trivial, just like the standard
4944 // mandates for the default constructor. This should rarely matter, because
4945 // the member will also be deleted.
4946 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4947 return true;
4948
4949 if (!SMOR->getMethod()) {
4950 assert(SMOR->getKind() ==
4951 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4952 return false;
4953 }
4954
4955 // We deliberately don't check if we found a deleted special member. We're
4956 // not supposed to!
4957 if (Selected)
4958 *Selected = SMOR->getMethod();
4959 return SMOR->getMethod()->isTrivial();
4960 }
4961
4962 llvm_unreachable("unknown special method kind");
4963}
4964
Benjamin Kramera574c892013-02-15 12:30:38 +00004965static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00004966 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4967 CI != CE; ++CI)
4968 if (!CI->isImplicit())
4969 return *CI;
4970
4971 // Look for constructor templates.
4972 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4973 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4974 if (CXXConstructorDecl *CD =
4975 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4976 return CD;
4977 }
4978
4979 return 0;
4980}
4981
4982/// The kind of subobject we are checking for triviality. The values of this
4983/// enumeration are used in diagnostics.
4984enum TrivialSubobjectKind {
4985 /// The subobject is a base class.
4986 TSK_BaseClass,
4987 /// The subobject is a non-static data member.
4988 TSK_Field,
4989 /// The object is actually the complete object.
4990 TSK_CompleteObject
4991};
4992
4993/// Check whether the special member selected for a given type would be trivial.
4994static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4995 QualType SubType,
4996 Sema::CXXSpecialMember CSM,
4997 TrivialSubobjectKind Kind,
4998 bool Diagnose) {
4999 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5000 if (!SubRD)
5001 return true;
5002
5003 CXXMethodDecl *Selected;
5004 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5005 Diagnose ? &Selected : 0))
5006 return true;
5007
5008 if (Diagnose) {
5009 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5010 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5011 << Kind << SubType.getUnqualifiedType();
5012 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5013 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5014 } else if (!Selected)
5015 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5016 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5017 else if (Selected->isUserProvided()) {
5018 if (Kind == TSK_CompleteObject)
5019 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5020 << Kind << SubType.getUnqualifiedType() << CSM;
5021 else {
5022 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5023 << Kind << SubType.getUnqualifiedType() << CSM;
5024 S.Diag(Selected->getLocation(), diag::note_declared_at);
5025 }
5026 } else {
5027 if (Kind != TSK_CompleteObject)
5028 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5029 << Kind << SubType.getUnqualifiedType() << CSM;
5030
5031 // Explain why the defaulted or deleted special member isn't trivial.
5032 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5033 }
5034 }
5035
5036 return false;
5037}
5038
5039/// Check whether the members of a class type allow a special member to be
5040/// trivial.
5041static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5042 Sema::CXXSpecialMember CSM,
5043 bool ConstArg, bool Diagnose) {
5044 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5045 FE = RD->field_end(); FI != FE; ++FI) {
5046 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5047 continue;
5048
5049 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5050
5051 // Pretend anonymous struct or union members are members of this class.
5052 if (FI->isAnonymousStructOrUnion()) {
5053 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5054 CSM, ConstArg, Diagnose))
5055 return false;
5056 continue;
5057 }
5058
5059 // C++11 [class.ctor]p5:
5060 // A default constructor is trivial if [...]
5061 // -- no non-static data member of its class has a
5062 // brace-or-equal-initializer
5063 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5064 if (Diagnose)
5065 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5066 return false;
5067 }
5068
5069 // Objective C ARC 4.3.5:
5070 // [...] nontrivally ownership-qualified types are [...] not trivially
5071 // default constructible, copy constructible, move constructible, copy
5072 // assignable, move assignable, or destructible [...]
5073 if (S.getLangOpts().ObjCAutoRefCount &&
5074 FieldType.hasNonTrivialObjCLifetime()) {
5075 if (Diagnose)
5076 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5077 << RD << FieldType.getObjCLifetime();
5078 return false;
5079 }
5080
5081 if (ConstArg && !FI->isMutable())
5082 FieldType.addConst();
5083 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5084 TSK_Field, Diagnose))
5085 return false;
5086 }
5087
5088 return true;
5089}
5090
5091/// Diagnose why the specified class does not have a trivial special member of
5092/// the given kind.
5093void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5094 QualType Ty = Context.getRecordType(RD);
5095 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5096 Ty.addConst();
5097
5098 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5099 TSK_CompleteObject, /*Diagnose*/true);
5100}
5101
5102/// Determine whether a defaulted or deleted special member function is trivial,
5103/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5104/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5105bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5106 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005107 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5108
5109 CXXRecordDecl *RD = MD->getParent();
5110
5111 bool ConstArg = false;
5112 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5113
5114 // C++11 [class.copy]p12, p25:
5115 // A [special member] is trivial if its declared parameter type is the same
5116 // as if it had been implicitly declared [...]
5117 switch (CSM) {
5118 case CXXDefaultConstructor:
5119 case CXXDestructor:
5120 // Trivial default constructors and destructors cannot have parameters.
5121 break;
5122
5123 case CXXCopyConstructor:
5124 case CXXCopyAssignment: {
5125 // Trivial copy operations always have const, non-volatile parameter types.
5126 ConstArg = true;
5127 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5128 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5129 if (Diagnose)
5130 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5131 << Param0->getSourceRange() << Param0->getType()
5132 << Context.getLValueReferenceType(
5133 Context.getRecordType(RD).withConst());
5134 return false;
5135 }
5136 break;
5137 }
5138
5139 case CXXMoveConstructor:
5140 case CXXMoveAssignment: {
5141 // Trivial move operations always have non-cv-qualified parameters.
5142 const RValueReferenceType *RT =
5143 Param0->getType()->getAs<RValueReferenceType>();
5144 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5145 if (Diagnose)
5146 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5147 << Param0->getSourceRange() << Param0->getType()
5148 << Context.getRValueReferenceType(Context.getRecordType(RD));
5149 return false;
5150 }
5151 break;
5152 }
5153
5154 case CXXInvalid:
5155 llvm_unreachable("not a special member");
5156 }
5157
5158 // FIXME: We require that the parameter-declaration-clause is equivalent to
5159 // that of an implicit declaration, not just that the declared parameter type
5160 // matches, in order to prevent absuridities like a function simultaneously
5161 // being a trivial copy constructor and a non-trivial default constructor.
5162 // This issue has not yet been assigned a core issue number.
5163 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5164 if (Diagnose)
5165 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5166 diag::note_nontrivial_default_arg)
5167 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5168 return false;
5169 }
5170 if (MD->isVariadic()) {
5171 if (Diagnose)
5172 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5173 return false;
5174 }
5175
5176 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5177 // A copy/move [constructor or assignment operator] is trivial if
5178 // -- the [member] selected to copy/move each direct base class subobject
5179 // is trivial
5180 //
5181 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5182 // A [default constructor or destructor] is trivial if
5183 // -- all the direct base classes have trivial [default constructors or
5184 // destructors]
5185 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5186 BE = RD->bases_end(); BI != BE; ++BI)
5187 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5188 ConstArg ? BI->getType().withConst()
5189 : BI->getType(),
5190 CSM, TSK_BaseClass, Diagnose))
5191 return false;
5192
5193 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5194 // A copy/move [constructor or assignment operator] for a class X is
5195 // trivial if
5196 // -- for each non-static data member of X that is of class type (or array
5197 // thereof), the constructor selected to copy/move that member is
5198 // trivial
5199 //
5200 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5201 // A [default constructor or destructor] is trivial if
5202 // -- for all of the non-static data members of its class that are of class
5203 // type (or array thereof), each such class has a trivial [default
5204 // constructor or destructor]
5205 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5206 return false;
5207
5208 // C++11 [class.dtor]p5:
5209 // A destructor is trivial if [...]
5210 // -- the destructor is not virtual
5211 if (CSM == CXXDestructor && MD->isVirtual()) {
5212 if (Diagnose)
5213 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5214 return false;
5215 }
5216
5217 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5218 // A [special member] for class X is trivial if [...]
5219 // -- class X has no virtual functions and no virtual base classes
5220 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5221 if (!Diagnose)
5222 return false;
5223
5224 if (RD->getNumVBases()) {
5225 // Check for virtual bases. We already know that the corresponding
5226 // member in all bases is trivial, so vbases must all be direct.
5227 CXXBaseSpecifier &BS = *RD->vbases_begin();
5228 assert(BS.isVirtual());
5229 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5230 return false;
5231 }
5232
5233 // Must have a virtual method.
5234 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5235 ME = RD->method_end(); MI != ME; ++MI) {
5236 if (MI->isVirtual()) {
5237 SourceLocation MLoc = MI->getLocStart();
5238 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5239 return false;
5240 }
5241 }
5242
5243 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5244 }
5245
5246 // Looks like it's trivial!
5247 return true;
5248}
5249
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005250/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005251namespace {
5252 struct FindHiddenVirtualMethodData {
5253 Sema *S;
5254 CXXMethodDecl *Method;
5255 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005256 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005257 };
5258}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005259
David Blaikie5f750682012-10-19 00:53:08 +00005260/// \brief Check whether any most overriden method from MD in Methods
5261static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5262 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5263 if (MD->size_overridden_methods() == 0)
5264 return Methods.count(MD->getCanonicalDecl());
5265 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5266 E = MD->end_overridden_methods();
5267 I != E; ++I)
5268 if (CheckMostOverridenMethods(*I, Methods))
5269 return true;
5270 return false;
5271}
5272
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005273/// \brief Member lookup function that determines whether a given C++
5274/// method overloads virtual methods in a base class without overriding any,
5275/// to be used with CXXRecordDecl::lookupInBases().
5276static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5277 CXXBasePath &Path,
5278 void *UserData) {
5279 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5280
5281 FindHiddenVirtualMethodData &Data
5282 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5283
5284 DeclarationName Name = Data.Method->getDeclName();
5285 assert(Name.getNameKind() == DeclarationName::Identifier);
5286
5287 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005288 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005289 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005290 !Path.Decls.empty();
5291 Path.Decls = Path.Decls.slice(1)) {
5292 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005293 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005294 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005295 foundSameNameMethod = true;
5296 // Interested only in hidden virtual methods.
5297 if (!MD->isVirtual())
5298 continue;
5299 // If the method we are checking overrides a method from its base
5300 // don't warn about the other overloaded methods.
5301 if (!Data.S->IsOverload(Data.Method, MD, false))
5302 return true;
5303 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005304 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005305 overloadedMethods.push_back(MD);
5306 }
5307 }
5308
5309 if (foundSameNameMethod)
5310 Data.OverloadedMethods.append(overloadedMethods.begin(),
5311 overloadedMethods.end());
5312 return foundSameNameMethod;
5313}
5314
David Blaikie5f750682012-10-19 00:53:08 +00005315/// \brief Add the most overriden methods from MD to Methods
5316static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5317 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5318 if (MD->size_overridden_methods() == 0)
5319 Methods.insert(MD->getCanonicalDecl());
5320 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5321 E = MD->end_overridden_methods();
5322 I != E; ++I)
5323 AddMostOverridenMethods(*I, Methods);
5324}
5325
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005326/// \brief See if a method overloads virtual methods in a base class without
5327/// overriding any.
5328void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5329 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005330 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005331 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005332 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005333 return;
5334
5335 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5336 /*bool RecordPaths=*/false,
5337 /*bool DetectVirtual=*/false);
5338 FindHiddenVirtualMethodData Data;
5339 Data.Method = MD;
5340 Data.S = this;
5341
5342 // Keep the base methods that were overriden or introduced in the subclass
5343 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005344 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5345 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5346 NamedDecl *ND = *I;
5347 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005348 ND = shad->getTargetDecl();
5349 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5350 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005351 }
5352
5353 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5354 !Data.OverloadedMethods.empty()) {
5355 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5356 << MD << (Data.OverloadedMethods.size() > 1);
5357
5358 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5359 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5360 Diag(overloadedMD->getLocation(),
5361 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5362 }
5363 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005364}
5365
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005366void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005367 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005368 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005369 SourceLocation RBrac,
5370 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005371 if (!TagDecl)
5372 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005373
Douglas Gregor42af25f2009-05-11 19:58:34 +00005374 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005375
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005376 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5377 if (l->getKind() != AttributeList::AT_Visibility)
5378 continue;
5379 l->setInvalid();
5380 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5381 l->getName();
5382 }
5383
David Blaikie77b6de02011-09-22 02:58:26 +00005384 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005385 // strict aliasing violation!
5386 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005387 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005388
Douglas Gregor23c94db2010-07-02 17:43:08 +00005389 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005390 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005391}
5392
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005393/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5394/// special functions, such as the default constructor, copy
5395/// constructor, or destructor, to the given C++ class (C++
5396/// [special]p1). This routine can only be executed just before the
5397/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005398void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005399 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005400 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005401
Richard Smithbc2a35d2012-12-08 08:32:28 +00005402 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005403 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005404
Richard Smithbc2a35d2012-12-08 08:32:28 +00005405 // If the properties or semantics of the copy constructor couldn't be
5406 // determined while the class was being declared, force a declaration
5407 // of it now.
5408 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5409 DeclareImplicitCopyConstructor(ClassDecl);
5410 }
5411
Richard Smith80ad52f2013-01-02 11:42:31 +00005412 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005413 ++ASTContext::NumImplicitMoveConstructors;
5414
Richard Smithbc2a35d2012-12-08 08:32:28 +00005415 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5416 DeclareImplicitMoveConstructor(ClassDecl);
5417 }
5418
Douglas Gregora376d102010-07-02 21:50:04 +00005419 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5420 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005421
5422 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005423 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005424 // it shows up in the right place in the vtable and that we diagnose
5425 // problems with the implicit exception specification.
5426 if (ClassDecl->isDynamicClass() ||
5427 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005428 DeclareImplicitCopyAssignment(ClassDecl);
5429 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005430
Richard Smith80ad52f2013-01-02 11:42:31 +00005431 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005432 ++ASTContext::NumImplicitMoveAssignmentOperators;
5433
5434 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005435 if (ClassDecl->isDynamicClass() ||
5436 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005437 DeclareImplicitMoveAssignment(ClassDecl);
5438 }
5439
Douglas Gregor4923aa22010-07-02 20:37:36 +00005440 if (!ClassDecl->hasUserDeclaredDestructor()) {
5441 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005442
5443 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005444 // have to declare the destructor immediately. This ensures that, e.g., it
5445 // shows up in the right place in the vtable and that we diagnose problems
5446 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005447 if (ClassDecl->isDynamicClass() ||
5448 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005449 DeclareImplicitDestructor(ClassDecl);
5450 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005451}
5452
Francois Pichet8387e2a2011-04-22 22:18:13 +00005453void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5454 if (!D)
5455 return;
5456
5457 int NumParamList = D->getNumTemplateParameterLists();
5458 for (int i = 0; i < NumParamList; i++) {
5459 TemplateParameterList* Params = D->getTemplateParameterList(i);
5460 for (TemplateParameterList::iterator Param = Params->begin(),
5461 ParamEnd = Params->end();
5462 Param != ParamEnd; ++Param) {
5463 NamedDecl *Named = cast<NamedDecl>(*Param);
5464 if (Named->getDeclName()) {
5465 S->AddDecl(Named);
5466 IdResolver.AddDecl(Named);
5467 }
5468 }
5469 }
5470}
5471
John McCalld226f652010-08-21 09:40:31 +00005472void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005473 if (!D)
5474 return;
5475
5476 TemplateParameterList *Params = 0;
5477 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5478 Params = Template->getTemplateParameters();
5479 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5480 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5481 Params = PartialSpec->getTemplateParameters();
5482 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005483 return;
5484
Douglas Gregor6569d682009-05-27 23:11:45 +00005485 for (TemplateParameterList::iterator Param = Params->begin(),
5486 ParamEnd = Params->end();
5487 Param != ParamEnd; ++Param) {
5488 NamedDecl *Named = cast<NamedDecl>(*Param);
5489 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005490 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005491 IdResolver.AddDecl(Named);
5492 }
5493 }
5494}
5495
John McCalld226f652010-08-21 09:40:31 +00005496void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005497 if (!RecordD) return;
5498 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005499 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005500 PushDeclContext(S, Record);
5501}
5502
John McCalld226f652010-08-21 09:40:31 +00005503void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005504 if (!RecordD) return;
5505 PopDeclContext();
5506}
5507
Douglas Gregor72b505b2008-12-16 21:30:33 +00005508/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5509/// parsing a top-level (non-nested) C++ class, and we are now
5510/// parsing those parts of the given Method declaration that could
5511/// not be parsed earlier (C++ [class.mem]p2), such as default
5512/// arguments. This action should enter the scope of the given
5513/// Method declaration as if we had just parsed the qualified method
5514/// name. However, it should not bring the parameters into scope;
5515/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005516void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005517}
5518
5519/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5520/// C++ method declaration. We're (re-)introducing the given
5521/// function parameter into scope for use in parsing later parts of
5522/// the method declaration. For example, we could see an
5523/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005524void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005525 if (!ParamD)
5526 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005527
John McCalld226f652010-08-21 09:40:31 +00005528 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005529
5530 // If this parameter has an unparsed default argument, clear it out
5531 // to make way for the parsed default argument.
5532 if (Param->hasUnparsedDefaultArg())
5533 Param->setDefaultArg(0);
5534
John McCalld226f652010-08-21 09:40:31 +00005535 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005536 if (Param->getDeclName())
5537 IdResolver.AddDecl(Param);
5538}
5539
5540/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5541/// processing the delayed method declaration for Method. The method
5542/// declaration is now considered finished. There may be a separate
5543/// ActOnStartOfFunctionDef action later (not necessarily
5544/// immediately!) for this method, if it was also defined inside the
5545/// class body.
John McCalld226f652010-08-21 09:40:31 +00005546void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005547 if (!MethodD)
5548 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005549
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005550 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005551
John McCalld226f652010-08-21 09:40:31 +00005552 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005553
5554 // Now that we have our default arguments, check the constructor
5555 // again. It could produce additional diagnostics or affect whether
5556 // the class has implicitly-declared destructors, among other
5557 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005558 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5559 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005560
5561 // Check the default arguments, which we may have added.
5562 if (!Method->isInvalidDecl())
5563 CheckCXXDefaultArguments(Method);
5564}
5565
Douglas Gregor42a552f2008-11-05 20:51:48 +00005566/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005567/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005568/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005569/// emit diagnostics and set the invalid bit to true. In any case, the type
5570/// will be updated to reflect a well-formed type for the constructor and
5571/// returned.
5572QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005573 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005574 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005575
5576 // C++ [class.ctor]p3:
5577 // A constructor shall not be virtual (10.3) or static (9.4). A
5578 // constructor can be invoked for a const, volatile or const
5579 // volatile object. A constructor shall not be declared const,
5580 // volatile, or const volatile (9.3.2).
5581 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005582 if (!D.isInvalidType())
5583 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5584 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5585 << SourceRange(D.getIdentifierLoc());
5586 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005587 }
John McCalld931b082010-08-26 03:08:43 +00005588 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005589 if (!D.isInvalidType())
5590 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5591 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5592 << SourceRange(D.getIdentifierLoc());
5593 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005594 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005595 }
Mike Stump1eb44332009-09-09 15:08:12 +00005596
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005597 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005598 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005599 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005600 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5601 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005602 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005603 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5604 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005605 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005606 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5607 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005608 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005609 }
Mike Stump1eb44332009-09-09 15:08:12 +00005610
Douglas Gregorc938c162011-01-26 05:01:58 +00005611 // C++0x [class.ctor]p4:
5612 // A constructor shall not be declared with a ref-qualifier.
5613 if (FTI.hasRefQualifier()) {
5614 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5615 << FTI.RefQualifierIsLValueRef
5616 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5617 D.setInvalidType();
5618 }
5619
Douglas Gregor42a552f2008-11-05 20:51:48 +00005620 // Rebuild the function type "R" without any type qualifiers (in
5621 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005622 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005623 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005624 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5625 return R;
5626
5627 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5628 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005629 EPI.RefQualifier = RQ_None;
5630
Chris Lattner65401802009-04-25 08:28:21 +00005631 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005632 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005633}
5634
Douglas Gregor72b505b2008-12-16 21:30:33 +00005635/// CheckConstructor - Checks a fully-formed constructor for
5636/// well-formedness, issuing any diagnostics required. Returns true if
5637/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005638void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005639 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005640 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5641 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005642 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005643
5644 // C++ [class.copy]p3:
5645 // A declaration of a constructor for a class X is ill-formed if
5646 // its first parameter is of type (optionally cv-qualified) X and
5647 // either there are no other parameters or else all other
5648 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005649 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005650 ((Constructor->getNumParams() == 1) ||
5651 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005652 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5653 Constructor->getTemplateSpecializationKind()
5654 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005655 QualType ParamType = Constructor->getParamDecl(0)->getType();
5656 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5657 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005658 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005659 const char *ConstRef
5660 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5661 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005662 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005663 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005664
5665 // FIXME: Rather that making the constructor invalid, we should endeavor
5666 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005667 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005668 }
5669 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005670}
5671
John McCall15442822010-08-04 01:04:25 +00005672/// CheckDestructor - Checks a fully-formed destructor definition for
5673/// well-formedness, issuing any diagnostics required. Returns true
5674/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005675bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005676 CXXRecordDecl *RD = Destructor->getParent();
5677
5678 if (Destructor->isVirtual()) {
5679 SourceLocation Loc;
5680
5681 if (!Destructor->isImplicit())
5682 Loc = Destructor->getLocation();
5683 else
5684 Loc = RD->getLocation();
5685
5686 // If we have a virtual destructor, look up the deallocation function
5687 FunctionDecl *OperatorDelete = 0;
5688 DeclarationName Name =
5689 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005690 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005691 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005692
Eli Friedman5f2987c2012-02-02 03:46:19 +00005693 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005694
5695 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005696 }
Anders Carlsson37909802009-11-30 21:24:50 +00005697
5698 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005699}
5700
Mike Stump1eb44332009-09-09 15:08:12 +00005701static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005702FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5703 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5704 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005705 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005706}
5707
Douglas Gregor42a552f2008-11-05 20:51:48 +00005708/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5709/// the well-formednes of the destructor declarator @p D with type @p
5710/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005711/// emit diagnostics and set the declarator to invalid. Even if this happens,
5712/// will be updated to reflect a well-formed type for the destructor and
5713/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005714QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005715 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005716 // C++ [class.dtor]p1:
5717 // [...] A typedef-name that names a class is a class-name
5718 // (7.1.3); however, a typedef-name that names a class shall not
5719 // be used as the identifier in the declarator for a destructor
5720 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005721 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005722 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005723 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005724 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005725 else if (const TemplateSpecializationType *TST =
5726 DeclaratorType->getAs<TemplateSpecializationType>())
5727 if (TST->isTypeAlias())
5728 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5729 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005730
5731 // C++ [class.dtor]p2:
5732 // A destructor is used to destroy objects of its class type. A
5733 // destructor takes no parameters, and no return type can be
5734 // specified for it (not even void). The address of a destructor
5735 // shall not be taken. A destructor shall not be static. A
5736 // destructor can be invoked for a const, volatile or const
5737 // volatile object. A destructor shall not be declared const,
5738 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005739 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005740 if (!D.isInvalidType())
5741 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5742 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005743 << SourceRange(D.getIdentifierLoc())
5744 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5745
John McCalld931b082010-08-26 03:08:43 +00005746 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005747 }
Chris Lattner65401802009-04-25 08:28:21 +00005748 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005749 // Destructors don't have return types, but the parser will
5750 // happily parse something like:
5751 //
5752 // class X {
5753 // float ~X();
5754 // };
5755 //
5756 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005757 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5758 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5759 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005760 }
Mike Stump1eb44332009-09-09 15:08:12 +00005761
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005762 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005763 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005764 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005765 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5766 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005767 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005768 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5769 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005770 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005771 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5772 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005773 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005774 }
5775
Douglas Gregorc938c162011-01-26 05:01:58 +00005776 // C++0x [class.dtor]p2:
5777 // A destructor shall not be declared with a ref-qualifier.
5778 if (FTI.hasRefQualifier()) {
5779 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5780 << FTI.RefQualifierIsLValueRef
5781 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5782 D.setInvalidType();
5783 }
5784
Douglas Gregor42a552f2008-11-05 20:51:48 +00005785 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005786 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005787 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5788
5789 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005790 FTI.freeArgs();
5791 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005792 }
5793
Mike Stump1eb44332009-09-09 15:08:12 +00005794 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005795 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005796 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005797 D.setInvalidType();
5798 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005799
5800 // Rebuild the function type "R" without any type qualifiers or
5801 // parameters (in case any of the errors above fired) and with
5802 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005803 // types.
John McCalle23cf432010-12-14 08:05:40 +00005804 if (!D.isInvalidType())
5805 return R;
5806
Douglas Gregord92ec472010-07-01 05:10:53 +00005807 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005808 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5809 EPI.Variadic = false;
5810 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005811 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005812 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005813}
5814
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005815/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5816/// well-formednes of the conversion function declarator @p D with
5817/// type @p R. If there are any errors in the declarator, this routine
5818/// will emit diagnostics and return true. Otherwise, it will return
5819/// false. Either way, the type @p R will be updated to reflect a
5820/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005821void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005822 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005823 // C++ [class.conv.fct]p1:
5824 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005825 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005826 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005827 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005828 if (!D.isInvalidType())
5829 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5830 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5831 << SourceRange(D.getIdentifierLoc());
5832 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005833 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005834 }
John McCalla3f81372010-04-13 00:04:31 +00005835
5836 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5837
Chris Lattner6e475012009-04-25 08:35:12 +00005838 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005839 // Conversion functions don't have return types, but the parser will
5840 // happily parse something like:
5841 //
5842 // class X {
5843 // float operator bool();
5844 // };
5845 //
5846 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005847 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5848 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5849 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005850 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005851 }
5852
John McCalla3f81372010-04-13 00:04:31 +00005853 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5854
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005855 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005856 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005857 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5858
5859 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005860 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005861 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005862 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005863 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005864 D.setInvalidType();
5865 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005866
John McCalla3f81372010-04-13 00:04:31 +00005867 // Diagnose "&operator bool()" and other such nonsense. This
5868 // is actually a gcc extension which we don't support.
5869 if (Proto->getResultType() != ConvType) {
5870 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5871 << Proto->getResultType();
5872 D.setInvalidType();
5873 ConvType = Proto->getResultType();
5874 }
5875
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005876 // C++ [class.conv.fct]p4:
5877 // The conversion-type-id shall not represent a function type nor
5878 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005879 if (ConvType->isArrayType()) {
5880 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5881 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005882 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005883 } else if (ConvType->isFunctionType()) {
5884 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5885 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005886 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005887 }
5888
5889 // Rebuild the function type "R" without any parameters (in case any
5890 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005891 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005892 if (D.isInvalidType())
5893 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005894
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005895 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005896 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005897 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005898 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005899 diag::warn_cxx98_compat_explicit_conversion_functions :
5900 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005901 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005902}
5903
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005904/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5905/// the declaration of the given C++ conversion function. This routine
5906/// is responsible for recording the conversion function in the C++
5907/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005908Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005909 assert(Conversion && "Expected to receive a conversion function declaration");
5910
Douglas Gregor9d350972008-12-12 08:25:50 +00005911 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005912
5913 // Make sure we aren't redeclaring the conversion function.
5914 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005915
5916 // C++ [class.conv.fct]p1:
5917 // [...] A conversion function is never used to convert a
5918 // (possibly cv-qualified) object to the (possibly cv-qualified)
5919 // same object type (or a reference to it), to a (possibly
5920 // cv-qualified) base class of that type (or a reference to it),
5921 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005922 // FIXME: Suppress this warning if the conversion function ends up being a
5923 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005924 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005925 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005926 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005927 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005928 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5929 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005930 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005931 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005932 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5933 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005934 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005935 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005936 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005937 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005938 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005939 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005940 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005941 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005942 }
5943
Douglas Gregore80622f2010-09-29 04:25:11 +00005944 if (FunctionTemplateDecl *ConversionTemplate
5945 = Conversion->getDescribedFunctionTemplate())
5946 return ConversionTemplate;
5947
John McCalld226f652010-08-21 09:40:31 +00005948 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005949}
5950
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005951//===----------------------------------------------------------------------===//
5952// Namespace Handling
5953//===----------------------------------------------------------------------===//
5954
Richard Smithd1a55a62012-10-04 22:13:39 +00005955/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5956/// reopened.
5957static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5958 SourceLocation Loc,
5959 IdentifierInfo *II, bool *IsInline,
5960 NamespaceDecl *PrevNS) {
5961 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005962
Richard Smithc969e6a2012-10-05 01:46:25 +00005963 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5964 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5965 // inline namespaces, with the intention of bringing names into namespace std.
5966 //
5967 // We support this just well enough to get that case working; this is not
5968 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005969 if (*IsInline && II && II->getName().startswith("__atomic") &&
5970 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005971 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005972 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5973 NS = NS->getPreviousDecl())
5974 NS->setInline(*IsInline);
5975 // Patch up the lookup table for the containing namespace. This isn't really
5976 // correct, but it's good enough for this particular case.
5977 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5978 E = PrevNS->decls_end(); I != E; ++I)
5979 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5980 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5981 return;
5982 }
5983
5984 if (PrevNS->isInline())
5985 // The user probably just forgot the 'inline', so suggest that it
5986 // be added back.
5987 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5988 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5989 else
5990 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5991 << IsInline;
5992
5993 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5994 *IsInline = PrevNS->isInline();
5995}
John McCallea318642010-08-26 09:15:37 +00005996
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005997/// ActOnStartNamespaceDef - This is called at the start of a namespace
5998/// definition.
John McCalld226f652010-08-21 09:40:31 +00005999Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006000 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006001 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006002 SourceLocation IdentLoc,
6003 IdentifierInfo *II,
6004 SourceLocation LBrace,
6005 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006006 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6007 // For anonymous namespace, take the location of the left brace.
6008 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006009 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006010 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006011 bool IsStd = false;
6012 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006013 Scope *DeclRegionScope = NamespcScope->getParent();
6014
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006015 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006016 if (II) {
6017 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006018 // The identifier in an original-namespace-definition shall not
6019 // have been previously defined in the declarative region in
6020 // which the original-namespace-definition appears. The
6021 // identifier in an original-namespace-definition is the name of
6022 // the namespace. Subsequently in that declarative region, it is
6023 // treated as an original-namespace-name.
6024 //
6025 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006026 // look through using directives, just look for any ordinary names.
6027
6028 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006029 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6030 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006031 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006032 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6033 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6034 ++I) {
6035 if ((*I)->getIdentifierNamespace() & IDNS) {
6036 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006037 break;
6038 }
6039 }
6040
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006041 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6042
6043 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006044 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006045 if (IsInline != PrevNS->isInline())
6046 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6047 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006048 } else if (PrevDecl) {
6049 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006050 Diag(Loc, diag::err_redefinition_different_kind)
6051 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006052 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006053 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006054 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006055 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006056 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006057 // This is the first "real" definition of the namespace "std", so update
6058 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006059 PrevNS = getStdNamespace();
6060 IsStd = true;
6061 AddToKnown = !IsInline;
6062 } else {
6063 // We've seen this namespace for the first time.
6064 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006065 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006066 } else {
John McCall9aeed322009-10-01 00:25:31 +00006067 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006068
6069 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006070 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006071 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006072 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006073 } else {
6074 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006075 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006076 }
6077
Richard Smithd1a55a62012-10-04 22:13:39 +00006078 if (PrevNS && IsInline != PrevNS->isInline())
6079 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6080 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006081 }
6082
6083 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6084 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006085 if (IsInvalid)
6086 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006087
6088 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006089
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006090 // FIXME: Should we be merging attributes?
6091 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006092 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006093
6094 if (IsStd)
6095 StdNamespace = Namespc;
6096 if (AddToKnown)
6097 KnownNamespaces[Namespc] = false;
6098
6099 if (II) {
6100 PushOnScopeChains(Namespc, DeclRegionScope);
6101 } else {
6102 // Link the anonymous namespace into its parent.
6103 DeclContext *Parent = CurContext->getRedeclContext();
6104 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6105 TU->setAnonymousNamespace(Namespc);
6106 } else {
6107 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006108 }
John McCall9aeed322009-10-01 00:25:31 +00006109
Douglas Gregora4181472010-03-24 00:46:35 +00006110 CurContext->addDecl(Namespc);
6111
John McCall9aeed322009-10-01 00:25:31 +00006112 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6113 // behaves as if it were replaced by
6114 // namespace unique { /* empty body */ }
6115 // using namespace unique;
6116 // namespace unique { namespace-body }
6117 // where all occurrences of 'unique' in a translation unit are
6118 // replaced by the same identifier and this identifier differs
6119 // from all other identifiers in the entire program.
6120
6121 // We just create the namespace with an empty name and then add an
6122 // implicit using declaration, just like the standard suggests.
6123 //
6124 // CodeGen enforces the "universally unique" aspect by giving all
6125 // declarations semantically contained within an anonymous
6126 // namespace internal linkage.
6127
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006128 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006129 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006130 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006131 /* 'using' */ LBrace,
6132 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006133 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006134 /* identifier */ SourceLocation(),
6135 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006136 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006137 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006138 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006139 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006140 }
6141
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006142 ActOnDocumentableDecl(Namespc);
6143
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006144 // Although we could have an invalid decl (i.e. the namespace name is a
6145 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006146 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6147 // for the namespace has the declarations that showed up in that particular
6148 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006149 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006150 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006151}
6152
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006153/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6154/// is a namespace alias, returns the namespace it points to.
6155static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6156 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6157 return AD->getNamespace();
6158 return dyn_cast_or_null<NamespaceDecl>(D);
6159}
6160
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006161/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6162/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006163void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006164 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6165 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006166 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006167 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006168 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006169 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006170}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006171
John McCall384aff82010-08-25 07:42:41 +00006172CXXRecordDecl *Sema::getStdBadAlloc() const {
6173 return cast_or_null<CXXRecordDecl>(
6174 StdBadAlloc.get(Context.getExternalSource()));
6175}
6176
6177NamespaceDecl *Sema::getStdNamespace() const {
6178 return cast_or_null<NamespaceDecl>(
6179 StdNamespace.get(Context.getExternalSource()));
6180}
6181
Douglas Gregor66992202010-06-29 17:53:46 +00006182/// \brief Retrieve the special "std" namespace, which may require us to
6183/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006184NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006185 if (!StdNamespace) {
6186 // The "std" namespace has not yet been defined, so build one implicitly.
6187 StdNamespace = NamespaceDecl::Create(Context,
6188 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006189 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006190 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006191 &PP.getIdentifierTable().get("std"),
6192 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006193 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006194 }
6195
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006196 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006197}
6198
Sebastian Redl395e04d2012-01-17 22:49:33 +00006199bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006200 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006201 "Looking for std::initializer_list outside of C++.");
6202
6203 // We're looking for implicit instantiations of
6204 // template <typename E> class std::initializer_list.
6205
6206 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6207 return false;
6208
Sebastian Redl84760e32012-01-17 22:49:58 +00006209 ClassTemplateDecl *Template = 0;
6210 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006211
Sebastian Redl84760e32012-01-17 22:49:58 +00006212 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006213
Sebastian Redl84760e32012-01-17 22:49:58 +00006214 ClassTemplateSpecializationDecl *Specialization =
6215 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6216 if (!Specialization)
6217 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006218
Sebastian Redl84760e32012-01-17 22:49:58 +00006219 Template = Specialization->getSpecializedTemplate();
6220 Arguments = Specialization->getTemplateArgs().data();
6221 } else if (const TemplateSpecializationType *TST =
6222 Ty->getAs<TemplateSpecializationType>()) {
6223 Template = dyn_cast_or_null<ClassTemplateDecl>(
6224 TST->getTemplateName().getAsTemplateDecl());
6225 Arguments = TST->getArgs();
6226 }
6227 if (!Template)
6228 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006229
6230 if (!StdInitializerList) {
6231 // Haven't recognized std::initializer_list yet, maybe this is it.
6232 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6233 if (TemplateClass->getIdentifier() !=
6234 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006235 !getStdNamespace()->InEnclosingNamespaceSetOf(
6236 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006237 return false;
6238 // This is a template called std::initializer_list, but is it the right
6239 // template?
6240 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006241 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006242 return false;
6243 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6244 return false;
6245
6246 // It's the right template.
6247 StdInitializerList = Template;
6248 }
6249
6250 if (Template != StdInitializerList)
6251 return false;
6252
6253 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006254 if (Element)
6255 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006256 return true;
6257}
6258
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006259static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6260 NamespaceDecl *Std = S.getStdNamespace();
6261 if (!Std) {
6262 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6263 return 0;
6264 }
6265
6266 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6267 Loc, Sema::LookupOrdinaryName);
6268 if (!S.LookupQualifiedName(Result, Std)) {
6269 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6270 return 0;
6271 }
6272 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6273 if (!Template) {
6274 Result.suppressDiagnostics();
6275 // We found something weird. Complain about the first thing we found.
6276 NamedDecl *Found = *Result.begin();
6277 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6278 return 0;
6279 }
6280
6281 // We found some template called std::initializer_list. Now verify that it's
6282 // correct.
6283 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006284 if (Params->getMinRequiredArguments() != 1 ||
6285 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006286 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6287 return 0;
6288 }
6289
6290 return Template;
6291}
6292
6293QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6294 if (!StdInitializerList) {
6295 StdInitializerList = LookupStdInitializerList(*this, Loc);
6296 if (!StdInitializerList)
6297 return QualType();
6298 }
6299
6300 TemplateArgumentListInfo Args(Loc, Loc);
6301 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6302 Context.getTrivialTypeSourceInfo(Element,
6303 Loc)));
6304 return Context.getCanonicalType(
6305 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6306}
6307
Sebastian Redl98d36062012-01-17 22:50:14 +00006308bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6309 // C++ [dcl.init.list]p2:
6310 // A constructor is an initializer-list constructor if its first parameter
6311 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6312 // std::initializer_list<E> for some type E, and either there are no other
6313 // parameters or else all other parameters have default arguments.
6314 if (Ctor->getNumParams() < 1 ||
6315 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6316 return false;
6317
6318 QualType ArgType = Ctor->getParamDecl(0)->getType();
6319 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6320 ArgType = RT->getPointeeType().getUnqualifiedType();
6321
6322 return isStdInitializerList(ArgType, 0);
6323}
6324
Douglas Gregor9172aa62011-03-26 22:25:30 +00006325/// \brief Determine whether a using statement is in a context where it will be
6326/// apply in all contexts.
6327static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6328 switch (CurContext->getDeclKind()) {
6329 case Decl::TranslationUnit:
6330 return true;
6331 case Decl::LinkageSpec:
6332 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6333 default:
6334 return false;
6335 }
6336}
6337
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006338namespace {
6339
6340// Callback to only accept typo corrections that are namespaces.
6341class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6342 public:
6343 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6344 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6345 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6346 }
6347 return false;
6348 }
6349};
6350
6351}
6352
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006353static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6354 CXXScopeSpec &SS,
6355 SourceLocation IdentLoc,
6356 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006357 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006358 R.clear();
6359 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006360 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006361 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006362 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6363 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006364 if (DeclContext *DC = S.computeDeclContext(SS, false))
6365 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6366 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006367 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6368 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006369 else
6370 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6371 << Ident << CorrectedQuotedStr
6372 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006373
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006374 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6375 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006376
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006377 R.addDecl(Corrected.getCorrectionDecl());
6378 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006379 }
6380 return false;
6381}
6382
John McCalld226f652010-08-21 09:40:31 +00006383Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006384 SourceLocation UsingLoc,
6385 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006386 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006387 SourceLocation IdentLoc,
6388 IdentifierInfo *NamespcName,
6389 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006390 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6391 assert(NamespcName && "Invalid NamespcName.");
6392 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006393
6394 // This can only happen along a recovery path.
6395 while (S->getFlags() & Scope::TemplateParamScope)
6396 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006397 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006398
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006399 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006400 NestedNameSpecifier *Qualifier = 0;
6401 if (SS.isSet())
6402 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6403
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006404 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006405 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6406 LookupParsedName(R, S, &SS);
6407 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006408 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006409
Douglas Gregor66992202010-06-29 17:53:46 +00006410 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006411 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006412 // Allow "using namespace std;" or "using namespace ::std;" even if
6413 // "std" hasn't been defined yet, for GCC compatibility.
6414 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6415 NamespcName->isStr("std")) {
6416 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006417 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006418 R.resolveKind();
6419 }
6420 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006421 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006422 }
6423
John McCallf36e02d2009-10-09 21:13:30 +00006424 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006425 NamedDecl *Named = R.getFoundDecl();
6426 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6427 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006428 // C++ [namespace.udir]p1:
6429 // A using-directive specifies that the names in the nominated
6430 // namespace can be used in the scope in which the
6431 // using-directive appears after the using-directive. During
6432 // unqualified name lookup (3.4.1), the names appear as if they
6433 // were declared in the nearest enclosing namespace which
6434 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006435 // namespace. [Note: in this context, "contains" means "contains
6436 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006437
6438 // Find enclosing context containing both using-directive and
6439 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006440 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006441 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6442 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6443 CommonAncestor = CommonAncestor->getParent();
6444
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006445 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006446 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006447 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006448
Douglas Gregor9172aa62011-03-26 22:25:30 +00006449 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006450 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006451 Diag(IdentLoc, diag::warn_using_directive_in_header);
6452 }
6453
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006454 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006455 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006456 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006457 }
6458
Richard Smith6b3d3e52013-02-20 19:22:51 +00006459 if (UDir)
6460 ProcessDeclAttributeList(S, UDir, AttrList);
6461
John McCalld226f652010-08-21 09:40:31 +00006462 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006463}
6464
6465void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006466 // If the scope has an associated entity and the using directive is at
6467 // namespace or translation unit scope, add the UsingDirectiveDecl into
6468 // its lookup structure so qualified name lookup can find it.
6469 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6470 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006471 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006472 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006473 // Otherwise, it is at block sope. The using-directives will affect lookup
6474 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006475 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006476}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006477
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006478
John McCalld226f652010-08-21 09:40:31 +00006479Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006480 AccessSpecifier AS,
6481 bool HasUsingKeyword,
6482 SourceLocation UsingLoc,
6483 CXXScopeSpec &SS,
6484 UnqualifiedId &Name,
6485 AttributeList *AttrList,
6486 bool IsTypeName,
6487 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006488 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006489
Douglas Gregor12c118a2009-11-04 16:30:06 +00006490 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006491 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006492 case UnqualifiedId::IK_Identifier:
6493 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006494 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006495 case UnqualifiedId::IK_ConversionFunctionId:
6496 break;
6497
6498 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006499 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006500 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006501 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006502 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006503 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6504 // instead once inheriting constructors work.
6505 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006506 diag::err_using_decl_constructor)
6507 << SS.getRange();
6508
Richard Smith80ad52f2013-01-02 11:42:31 +00006509 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006510
John McCalld226f652010-08-21 09:40:31 +00006511 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006512
6513 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006514 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006515 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006516 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006517
6518 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006519 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006520 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006521 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006522 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006523
6524 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6525 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006526 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006527 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006528
John McCall60fa3cf2009-12-11 02:10:03 +00006529 // Warn about using declarations.
6530 // TODO: store that the declaration was written without 'using' and
6531 // talk about access decls instead of using decls in the
6532 // diagnostics.
6533 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006534 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006535
6536 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006537 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006538 }
6539
Douglas Gregor56c04582010-12-16 00:46:58 +00006540 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6541 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6542 return 0;
6543
John McCall9488ea12009-11-17 05:59:44 +00006544 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006545 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006546 /* IsInstantiation */ false,
6547 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006548 if (UD)
6549 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006550
John McCalld226f652010-08-21 09:40:31 +00006551 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006552}
6553
Douglas Gregor09acc982010-07-07 23:08:52 +00006554/// \brief Determine whether a using declaration considers the given
6555/// declarations as "equivalent", e.g., if they are redeclarations of
6556/// the same entity or are both typedefs of the same type.
6557static bool
6558IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6559 bool &SuppressRedeclaration) {
6560 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6561 SuppressRedeclaration = false;
6562 return true;
6563 }
6564
Richard Smith162e1c12011-04-15 14:24:37 +00006565 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6566 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006567 SuppressRedeclaration = true;
6568 return Context.hasSameType(TD1->getUnderlyingType(),
6569 TD2->getUnderlyingType());
6570 }
6571
6572 return false;
6573}
6574
6575
John McCall9f54ad42009-12-10 09:41:52 +00006576/// Determines whether to create a using shadow decl for a particular
6577/// decl, given the set of decls existing prior to this using lookup.
6578bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6579 const LookupResult &Previous) {
6580 // Diagnose finding a decl which is not from a base class of the
6581 // current class. We do this now because there are cases where this
6582 // function will silently decide not to build a shadow decl, which
6583 // will pre-empt further diagnostics.
6584 //
6585 // We don't need to do this in C++0x because we do the check once on
6586 // the qualifier.
6587 //
6588 // FIXME: diagnose the following if we care enough:
6589 // struct A { int foo; };
6590 // struct B : A { using A::foo; };
6591 // template <class T> struct C : A {};
6592 // template <class T> struct D : C<T> { using B::foo; } // <---
6593 // This is invalid (during instantiation) in C++03 because B::foo
6594 // resolves to the using decl in B, which is not a base class of D<T>.
6595 // We can't diagnose it immediately because C<T> is an unknown
6596 // specialization. The UsingShadowDecl in D<T> then points directly
6597 // to A::foo, which will look well-formed when we instantiate.
6598 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006599 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006600 DeclContext *OrigDC = Orig->getDeclContext();
6601
6602 // Handle enums and anonymous structs.
6603 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6604 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6605 while (OrigRec->isAnonymousStructOrUnion())
6606 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6607
6608 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6609 if (OrigDC == CurContext) {
6610 Diag(Using->getLocation(),
6611 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006612 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006613 Diag(Orig->getLocation(), diag::note_using_decl_target);
6614 return true;
6615 }
6616
Douglas Gregordc355712011-02-25 00:36:19 +00006617 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006618 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006619 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006620 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006621 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006622 Diag(Orig->getLocation(), diag::note_using_decl_target);
6623 return true;
6624 }
6625 }
6626
6627 if (Previous.empty()) return false;
6628
6629 NamedDecl *Target = Orig;
6630 if (isa<UsingShadowDecl>(Target))
6631 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6632
John McCalld7533ec2009-12-11 02:33:26 +00006633 // If the target happens to be one of the previous declarations, we
6634 // don't have a conflict.
6635 //
6636 // FIXME: but we might be increasing its access, in which case we
6637 // should redeclare it.
6638 NamedDecl *NonTag = 0, *Tag = 0;
6639 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6640 I != E; ++I) {
6641 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006642 bool Result;
6643 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6644 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006645
6646 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6647 }
6648
John McCall9f54ad42009-12-10 09:41:52 +00006649 if (Target->isFunctionOrFunctionTemplate()) {
6650 FunctionDecl *FD;
6651 if (isa<FunctionTemplateDecl>(Target))
6652 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6653 else
6654 FD = cast<FunctionDecl>(Target);
6655
6656 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006657 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006658 case Ovl_Overload:
6659 return false;
6660
6661 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006662 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006663 break;
6664
6665 // We found a decl with the exact signature.
6666 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006667 // If we're in a record, we want to hide the target, so we
6668 // return true (without a diagnostic) to tell the caller not to
6669 // build a shadow decl.
6670 if (CurContext->isRecord())
6671 return true;
6672
6673 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006674 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006675 break;
6676 }
6677
6678 Diag(Target->getLocation(), diag::note_using_decl_target);
6679 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6680 return true;
6681 }
6682
6683 // Target is not a function.
6684
John McCall9f54ad42009-12-10 09:41:52 +00006685 if (isa<TagDecl>(Target)) {
6686 // No conflict between a tag and a non-tag.
6687 if (!Tag) return false;
6688
John McCall41ce66f2009-12-10 19:51:03 +00006689 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006690 Diag(Target->getLocation(), diag::note_using_decl_target);
6691 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6692 return true;
6693 }
6694
6695 // No conflict between a tag and a non-tag.
6696 if (!NonTag) return false;
6697
John McCall41ce66f2009-12-10 19:51:03 +00006698 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006699 Diag(Target->getLocation(), diag::note_using_decl_target);
6700 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6701 return true;
6702}
6703
John McCall9488ea12009-11-17 05:59:44 +00006704/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006705UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006706 UsingDecl *UD,
6707 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006708
6709 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006710 NamedDecl *Target = Orig;
6711 if (isa<UsingShadowDecl>(Target)) {
6712 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6713 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006714 }
6715
6716 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006717 = UsingShadowDecl::Create(Context, CurContext,
6718 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006719 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006720
6721 Shadow->setAccess(UD->getAccess());
6722 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6723 Shadow->setInvalidDecl();
6724
John McCall9488ea12009-11-17 05:59:44 +00006725 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006726 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006727 else
John McCall604e7f12009-12-08 07:46:18 +00006728 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006729
John McCall604e7f12009-12-08 07:46:18 +00006730
John McCall9f54ad42009-12-10 09:41:52 +00006731 return Shadow;
6732}
John McCall604e7f12009-12-08 07:46:18 +00006733
John McCall9f54ad42009-12-10 09:41:52 +00006734/// Hides a using shadow declaration. This is required by the current
6735/// using-decl implementation when a resolvable using declaration in a
6736/// class is followed by a declaration which would hide or override
6737/// one or more of the using decl's targets; for example:
6738///
6739/// struct Base { void foo(int); };
6740/// struct Derived : Base {
6741/// using Base::foo;
6742/// void foo(int);
6743/// };
6744///
6745/// The governing language is C++03 [namespace.udecl]p12:
6746///
6747/// When a using-declaration brings names from a base class into a
6748/// derived class scope, member functions in the derived class
6749/// override and/or hide member functions with the same name and
6750/// parameter types in a base class (rather than conflicting).
6751///
6752/// There are two ways to implement this:
6753/// (1) optimistically create shadow decls when they're not hidden
6754/// by existing declarations, or
6755/// (2) don't create any shadow decls (or at least don't make them
6756/// visible) until we've fully parsed/instantiated the class.
6757/// The problem with (1) is that we might have to retroactively remove
6758/// a shadow decl, which requires several O(n) operations because the
6759/// decl structures are (very reasonably) not designed for removal.
6760/// (2) avoids this but is very fiddly and phase-dependent.
6761void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006762 if (Shadow->getDeclName().getNameKind() ==
6763 DeclarationName::CXXConversionFunctionName)
6764 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6765
John McCall9f54ad42009-12-10 09:41:52 +00006766 // Remove it from the DeclContext...
6767 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006768
John McCall9f54ad42009-12-10 09:41:52 +00006769 // ...and the scope, if applicable...
6770 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006771 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006772 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006773 }
6774
John McCall9f54ad42009-12-10 09:41:52 +00006775 // ...and the using decl.
6776 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6777
6778 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006779 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006780}
6781
John McCall7ba107a2009-11-18 02:36:19 +00006782/// Builds a using declaration.
6783///
6784/// \param IsInstantiation - Whether this call arises from an
6785/// instantiation of an unresolved using declaration. We treat
6786/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006787NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6788 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006789 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006790 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006791 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006792 bool IsInstantiation,
6793 bool IsTypeName,
6794 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006795 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006796 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006797 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006798
Anders Carlsson550b14b2009-08-28 05:49:21 +00006799 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006800
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006801 if (SS.isEmpty()) {
6802 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006803 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006804 }
Mike Stump1eb44332009-09-09 15:08:12 +00006805
John McCall9f54ad42009-12-10 09:41:52 +00006806 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006807 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006808 ForRedeclaration);
6809 Previous.setHideTags(false);
6810 if (S) {
6811 LookupName(Previous, S);
6812
6813 // It is really dumb that we have to do this.
6814 LookupResult::Filter F = Previous.makeFilter();
6815 while (F.hasNext()) {
6816 NamedDecl *D = F.next();
6817 if (!isDeclInScope(D, CurContext, S))
6818 F.erase();
6819 }
6820 F.done();
6821 } else {
6822 assert(IsInstantiation && "no scope in non-instantiation");
6823 assert(CurContext->isRecord() && "scope not record in instantiation");
6824 LookupQualifiedName(Previous, CurContext);
6825 }
6826
John McCall9f54ad42009-12-10 09:41:52 +00006827 // Check for invalid redeclarations.
6828 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6829 return 0;
6830
6831 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006832 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6833 return 0;
6834
John McCallaf8e6ed2009-11-12 03:15:40 +00006835 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006836 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006837 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006838 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006839 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006840 // FIXME: not all declaration name kinds are legal here
6841 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6842 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006843 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006844 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006845 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006846 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6847 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006848 }
John McCalled976492009-12-04 22:46:56 +00006849 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006850 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6851 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006852 }
John McCalled976492009-12-04 22:46:56 +00006853 D->setAccess(AS);
6854 CurContext->addDecl(D);
6855
6856 if (!LookupContext) return D;
6857 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006858
John McCall77bb1aa2010-05-01 00:40:08 +00006859 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006860 UD->setInvalidDecl();
6861 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006862 }
6863
Richard Smithc5a89a12012-04-02 01:30:27 +00006864 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006865 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006866 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006867 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006868 return UD;
6869 }
6870
6871 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006872
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006873 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006874
John McCall604e7f12009-12-08 07:46:18 +00006875 // Unlike most lookups, we don't always want to hide tag
6876 // declarations: tag names are visible through the using declaration
6877 // even if hidden by ordinary names, *except* in a dependent context
6878 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006879 if (!IsInstantiation)
6880 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006881
John McCallb9abd8722012-04-07 03:04:20 +00006882 // For the purposes of this lookup, we have a base object type
6883 // equal to that of the current context.
6884 if (CurContext->isRecord()) {
6885 R.setBaseObjectType(
6886 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6887 }
6888
John McCalla24dc2e2009-11-17 02:14:36 +00006889 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006890
John McCallf36e02d2009-10-09 21:13:30 +00006891 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006892 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006893 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006894 UD->setInvalidDecl();
6895 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006896 }
6897
John McCalled976492009-12-04 22:46:56 +00006898 if (R.isAmbiguous()) {
6899 UD->setInvalidDecl();
6900 return UD;
6901 }
Mike Stump1eb44332009-09-09 15:08:12 +00006902
John McCall7ba107a2009-11-18 02:36:19 +00006903 if (IsTypeName) {
6904 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006905 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006906 Diag(IdentLoc, diag::err_using_typename_non_type);
6907 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6908 Diag((*I)->getUnderlyingDecl()->getLocation(),
6909 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006910 UD->setInvalidDecl();
6911 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006912 }
6913 } else {
6914 // If we asked for a non-typename and we got a type, error out,
6915 // but only if this is an instantiation of an unresolved using
6916 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006917 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006918 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6919 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006920 UD->setInvalidDecl();
6921 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006922 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006923 }
6924
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006925 // C++0x N2914 [namespace.udecl]p6:
6926 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006927 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006928 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6929 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006930 UD->setInvalidDecl();
6931 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006932 }
Mike Stump1eb44332009-09-09 15:08:12 +00006933
John McCall9f54ad42009-12-10 09:41:52 +00006934 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6935 if (!CheckUsingShadowDecl(UD, *I, Previous))
6936 BuildUsingShadowDecl(S, UD, *I);
6937 }
John McCall9488ea12009-11-17 05:59:44 +00006938
6939 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006940}
6941
Sebastian Redlf677ea32011-02-05 19:23:19 +00006942/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006943bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6944 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006945
Douglas Gregordc355712011-02-25 00:36:19 +00006946 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006947 assert(SourceType &&
6948 "Using decl naming constructor doesn't have type in scope spec.");
6949 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6950
6951 // Check whether the named type is a direct base class.
6952 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6953 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6954 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6955 BaseIt != BaseE; ++BaseIt) {
6956 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6957 if (CanonicalSourceType == BaseType)
6958 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006959 if (BaseIt->getType()->isDependentType())
6960 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006961 }
6962
6963 if (BaseIt == BaseE) {
6964 // Did not find SourceType in the bases.
6965 Diag(UD->getUsingLocation(),
6966 diag::err_using_decl_constructor_not_in_direct_base)
6967 << UD->getNameInfo().getSourceRange()
6968 << QualType(SourceType, 0) << TargetClass;
6969 return true;
6970 }
6971
Richard Smithc5a89a12012-04-02 01:30:27 +00006972 if (!CurContext->isDependentContext())
6973 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006974
6975 return false;
6976}
6977
John McCall9f54ad42009-12-10 09:41:52 +00006978/// Checks that the given using declaration is not an invalid
6979/// redeclaration. Note that this is checking only for the using decl
6980/// itself, not for any ill-formedness among the UsingShadowDecls.
6981bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6982 bool isTypeName,
6983 const CXXScopeSpec &SS,
6984 SourceLocation NameLoc,
6985 const LookupResult &Prev) {
6986 // C++03 [namespace.udecl]p8:
6987 // C++0x [namespace.udecl]p10:
6988 // A using-declaration is a declaration and can therefore be used
6989 // repeatedly where (and only where) multiple declarations are
6990 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006991 //
John McCall8a726212010-11-29 18:01:58 +00006992 // That's in non-member contexts.
6993 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006994 return false;
6995
6996 NestedNameSpecifier *Qual
6997 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6998
6999 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7000 NamedDecl *D = *I;
7001
7002 bool DTypename;
7003 NestedNameSpecifier *DQual;
7004 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7005 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007006 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007007 } else if (UnresolvedUsingValueDecl *UD
7008 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7009 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007010 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007011 } else if (UnresolvedUsingTypenameDecl *UD
7012 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7013 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007014 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007015 } else continue;
7016
7017 // using decls differ if one says 'typename' and the other doesn't.
7018 // FIXME: non-dependent using decls?
7019 if (isTypeName != DTypename) continue;
7020
7021 // using decls differ if they name different scopes (but note that
7022 // template instantiation can cause this check to trigger when it
7023 // didn't before instantiation).
7024 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7025 Context.getCanonicalNestedNameSpecifier(DQual))
7026 continue;
7027
7028 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007029 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007030 return true;
7031 }
7032
7033 return false;
7034}
7035
John McCall604e7f12009-12-08 07:46:18 +00007036
John McCalled976492009-12-04 22:46:56 +00007037/// Checks that the given nested-name qualifier used in a using decl
7038/// in the current context is appropriately related to the current
7039/// scope. If an error is found, diagnoses it and returns true.
7040bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7041 const CXXScopeSpec &SS,
7042 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007043 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007044
John McCall604e7f12009-12-08 07:46:18 +00007045 if (!CurContext->isRecord()) {
7046 // C++03 [namespace.udecl]p3:
7047 // C++0x [namespace.udecl]p8:
7048 // A using-declaration for a class member shall be a member-declaration.
7049
7050 // If we weren't able to compute a valid scope, it must be a
7051 // dependent class scope.
7052 if (!NamedContext || NamedContext->isRecord()) {
7053 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7054 << SS.getRange();
7055 return true;
7056 }
7057
7058 // Otherwise, everything is known to be fine.
7059 return false;
7060 }
7061
7062 // The current scope is a record.
7063
7064 // If the named context is dependent, we can't decide much.
7065 if (!NamedContext) {
7066 // FIXME: in C++0x, we can diagnose if we can prove that the
7067 // nested-name-specifier does not refer to a base class, which is
7068 // still possible in some cases.
7069
7070 // Otherwise we have to conservatively report that things might be
7071 // okay.
7072 return false;
7073 }
7074
7075 if (!NamedContext->isRecord()) {
7076 // Ideally this would point at the last name in the specifier,
7077 // but we don't have that level of source info.
7078 Diag(SS.getRange().getBegin(),
7079 diag::err_using_decl_nested_name_specifier_is_not_class)
7080 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7081 return true;
7082 }
7083
Douglas Gregor6fb07292010-12-21 07:41:49 +00007084 if (!NamedContext->isDependentContext() &&
7085 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7086 return true;
7087
Richard Smith80ad52f2013-01-02 11:42:31 +00007088 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007089 // C++0x [namespace.udecl]p3:
7090 // In a using-declaration used as a member-declaration, the
7091 // nested-name-specifier shall name a base class of the class
7092 // being defined.
7093
7094 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7095 cast<CXXRecordDecl>(NamedContext))) {
7096 if (CurContext == NamedContext) {
7097 Diag(NameLoc,
7098 diag::err_using_decl_nested_name_specifier_is_current_class)
7099 << SS.getRange();
7100 return true;
7101 }
7102
7103 Diag(SS.getRange().getBegin(),
7104 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7105 << (NestedNameSpecifier*) SS.getScopeRep()
7106 << cast<CXXRecordDecl>(CurContext)
7107 << SS.getRange();
7108 return true;
7109 }
7110
7111 return false;
7112 }
7113
7114 // C++03 [namespace.udecl]p4:
7115 // A using-declaration used as a member-declaration shall refer
7116 // to a member of a base class of the class being defined [etc.].
7117
7118 // Salient point: SS doesn't have to name a base class as long as
7119 // lookup only finds members from base classes. Therefore we can
7120 // diagnose here only if we can prove that that can't happen,
7121 // i.e. if the class hierarchies provably don't intersect.
7122
7123 // TODO: it would be nice if "definitely valid" results were cached
7124 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7125 // need to be repeated.
7126
7127 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007128 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007129
7130 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7131 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7132 Data->Bases.insert(Base);
7133 return true;
7134 }
7135
7136 bool hasDependentBases(const CXXRecordDecl *Class) {
7137 return !Class->forallBases(collect, this);
7138 }
7139
7140 /// Returns true if the base is dependent or is one of the
7141 /// accumulated base classes.
7142 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7143 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7144 return !Data->Bases.count(Base);
7145 }
7146
7147 bool mightShareBases(const CXXRecordDecl *Class) {
7148 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7149 }
7150 };
7151
7152 UserData Data;
7153
7154 // Returns false if we find a dependent base.
7155 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7156 return false;
7157
7158 // Returns false if the class has a dependent base or if it or one
7159 // of its bases is present in the base set of the current context.
7160 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7161 return false;
7162
7163 Diag(SS.getRange().getBegin(),
7164 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7165 << (NestedNameSpecifier*) SS.getScopeRep()
7166 << cast<CXXRecordDecl>(CurContext)
7167 << SS.getRange();
7168
7169 return true;
John McCalled976492009-12-04 22:46:56 +00007170}
7171
Richard Smith162e1c12011-04-15 14:24:37 +00007172Decl *Sema::ActOnAliasDeclaration(Scope *S,
7173 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007174 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007175 SourceLocation UsingLoc,
7176 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007177 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007178 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007179 // Skip up to the relevant declaration scope.
7180 while (S->getFlags() & Scope::TemplateParamScope)
7181 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007182 assert((S->getFlags() & Scope::DeclScope) &&
7183 "got alias-declaration outside of declaration scope");
7184
7185 if (Type.isInvalid())
7186 return 0;
7187
7188 bool Invalid = false;
7189 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7190 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007191 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007192
7193 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7194 return 0;
7195
7196 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007197 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007198 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007199 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7200 TInfo->getTypeLoc().getBeginLoc());
7201 }
Richard Smith162e1c12011-04-15 14:24:37 +00007202
7203 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7204 LookupName(Previous, S);
7205
7206 // Warn about shadowing the name of a template parameter.
7207 if (Previous.isSingleResult() &&
7208 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007209 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007210 Previous.clear();
7211 }
7212
7213 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7214 "name in alias declaration must be an identifier");
7215 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7216 Name.StartLocation,
7217 Name.Identifier, TInfo);
7218
7219 NewTD->setAccess(AS);
7220
7221 if (Invalid)
7222 NewTD->setInvalidDecl();
7223
Richard Smith6b3d3e52013-02-20 19:22:51 +00007224 ProcessDeclAttributeList(S, NewTD, AttrList);
7225
Richard Smith3e4c6c42011-05-05 21:57:07 +00007226 CheckTypedefForVariablyModifiedType(S, NewTD);
7227 Invalid |= NewTD->isInvalidDecl();
7228
Richard Smith162e1c12011-04-15 14:24:37 +00007229 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007230
7231 NamedDecl *NewND;
7232 if (TemplateParamLists.size()) {
7233 TypeAliasTemplateDecl *OldDecl = 0;
7234 TemplateParameterList *OldTemplateParams = 0;
7235
7236 if (TemplateParamLists.size() != 1) {
7237 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007238 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7239 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007240 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007241 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007242
7243 // Only consider previous declarations in the same scope.
7244 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7245 /*ExplicitInstantiationOrSpecialization*/false);
7246 if (!Previous.empty()) {
7247 Redeclaration = true;
7248
7249 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7250 if (!OldDecl && !Invalid) {
7251 Diag(UsingLoc, diag::err_redefinition_different_kind)
7252 << Name.Identifier;
7253
7254 NamedDecl *OldD = Previous.getRepresentativeDecl();
7255 if (OldD->getLocation().isValid())
7256 Diag(OldD->getLocation(), diag::note_previous_definition);
7257
7258 Invalid = true;
7259 }
7260
7261 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7262 if (TemplateParameterListsAreEqual(TemplateParams,
7263 OldDecl->getTemplateParameters(),
7264 /*Complain=*/true,
7265 TPL_TemplateMatch))
7266 OldTemplateParams = OldDecl->getTemplateParameters();
7267 else
7268 Invalid = true;
7269
7270 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7271 if (!Invalid &&
7272 !Context.hasSameType(OldTD->getUnderlyingType(),
7273 NewTD->getUnderlyingType())) {
7274 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7275 // but we can't reasonably accept it.
7276 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7277 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7278 if (OldTD->getLocation().isValid())
7279 Diag(OldTD->getLocation(), diag::note_previous_definition);
7280 Invalid = true;
7281 }
7282 }
7283 }
7284
7285 // Merge any previous default template arguments into our parameters,
7286 // and check the parameter list.
7287 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7288 TPC_TypeAliasTemplate))
7289 return 0;
7290
7291 TypeAliasTemplateDecl *NewDecl =
7292 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7293 Name.Identifier, TemplateParams,
7294 NewTD);
7295
7296 NewDecl->setAccess(AS);
7297
7298 if (Invalid)
7299 NewDecl->setInvalidDecl();
7300 else if (OldDecl)
7301 NewDecl->setPreviousDeclaration(OldDecl);
7302
7303 NewND = NewDecl;
7304 } else {
7305 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7306 NewND = NewTD;
7307 }
Richard Smith162e1c12011-04-15 14:24:37 +00007308
7309 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007310 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007311
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007312 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007313 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007314}
7315
John McCalld226f652010-08-21 09:40:31 +00007316Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007317 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007318 SourceLocation AliasLoc,
7319 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007320 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007321 SourceLocation IdentLoc,
7322 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007323
Anders Carlsson81c85c42009-03-28 23:53:49 +00007324 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007325 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7326 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007327
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007328 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007329 NamedDecl *PrevDecl
7330 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7331 ForRedeclaration);
7332 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7333 PrevDecl = 0;
7334
7335 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007336 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007337 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007338 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007339 // FIXME: At some point, we'll want to create the (redundant)
7340 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007341 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007342 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007343 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007344 }
Mike Stump1eb44332009-09-09 15:08:12 +00007345
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007346 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7347 diag::err_redefinition_different_kind;
7348 Diag(AliasLoc, DiagID) << Alias;
7349 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007350 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007351 }
7352
John McCalla24dc2e2009-11-17 02:14:36 +00007353 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007354 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007355
John McCallf36e02d2009-10-09 21:13:30 +00007356 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007357 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007358 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007359 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007360 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007361 }
Mike Stump1eb44332009-09-09 15:08:12 +00007362
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007363 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007364 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007365 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007366 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007367
John McCall3dbd3d52010-02-16 06:53:13 +00007368 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007369 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007370}
7371
Sean Hunt001cad92011-05-10 00:49:42 +00007372Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007373Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7374 CXXMethodDecl *MD) {
7375 CXXRecordDecl *ClassDecl = MD->getParent();
7376
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007377 // C++ [except.spec]p14:
7378 // An implicitly declared special member function (Clause 12) shall have an
7379 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007380 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007381 if (ClassDecl->isInvalidDecl())
7382 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007383
Sebastian Redl60618fa2011-03-12 11:50:43 +00007384 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007385 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7386 BEnd = ClassDecl->bases_end();
7387 B != BEnd; ++B) {
7388 if (B->isVirtual()) // Handled below.
7389 continue;
7390
Douglas Gregor18274032010-07-03 00:47:00 +00007391 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7392 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007393 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7394 // If this is a deleted function, add it anyway. This might be conformant
7395 // with the standard. This might not. I'm not sure. It might not matter.
7396 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007397 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007398 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007399 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007400
7401 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007402 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7403 BEnd = ClassDecl->vbases_end();
7404 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007405 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7406 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007407 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7408 // If this is a deleted function, add it anyway. This might be conformant
7409 // with the standard. This might not. I'm not sure. It might not matter.
7410 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007411 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007412 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007413 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007414
7415 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007416 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7417 FEnd = ClassDecl->field_end();
7418 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007419 if (F->hasInClassInitializer()) {
7420 if (Expr *E = F->getInClassInitializer())
7421 ExceptSpec.CalledExpr(E);
7422 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007423 // DR1351:
7424 // If the brace-or-equal-initializer of a non-static data member
7425 // invokes a defaulted default constructor of its class or of an
7426 // enclosing class in a potentially evaluated subexpression, the
7427 // program is ill-formed.
7428 //
7429 // This resolution is unworkable: the exception specification of the
7430 // default constructor can be needed in an unevaluated context, in
7431 // particular, in the operand of a noexcept-expression, and we can be
7432 // unable to compute an exception specification for an enclosed class.
7433 //
7434 // We do not allow an in-class initializer to require the evaluation
7435 // of the exception specification for any in-class initializer whose
7436 // definition is not lexically complete.
7437 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007438 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007439 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007440 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7441 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7442 // If this is a deleted function, add it anyway. This might be conformant
7443 // with the standard. This might not. I'm not sure. It might not matter.
7444 // In particular, the problem is that this function never gets called. It
7445 // might just be ill-formed because this function attempts to refer to
7446 // a deleted function here.
7447 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007448 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007449 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007450 }
John McCalle23cf432010-12-14 08:05:40 +00007451
Sean Hunt001cad92011-05-10 00:49:42 +00007452 return ExceptSpec;
7453}
7454
Richard Smithafb49182012-11-29 01:34:07 +00007455namespace {
7456/// RAII object to register a special member as being currently declared.
7457struct DeclaringSpecialMember {
7458 Sema &S;
7459 Sema::SpecialMemberDecl D;
7460 bool WasAlreadyBeingDeclared;
7461
7462 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7463 : S(S), D(RD, CSM) {
7464 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7465 if (WasAlreadyBeingDeclared)
7466 // This almost never happens, but if it does, ensure that our cache
7467 // doesn't contain a stale result.
7468 S.SpecialMemberCache.clear();
7469
7470 // FIXME: Register a note to be produced if we encounter an error while
7471 // declaring the special member.
7472 }
7473 ~DeclaringSpecialMember() {
7474 if (!WasAlreadyBeingDeclared)
7475 S.SpecialMembersBeingDeclared.erase(D);
7476 }
7477
7478 /// \brief Are we already trying to declare this special member?
7479 bool isAlreadyBeingDeclared() const {
7480 return WasAlreadyBeingDeclared;
7481 }
7482};
7483}
7484
Sean Hunt001cad92011-05-10 00:49:42 +00007485CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7486 CXXRecordDecl *ClassDecl) {
7487 // C++ [class.ctor]p5:
7488 // A default constructor for a class X is a constructor of class X
7489 // that can be called without an argument. If there is no
7490 // user-declared constructor for class X, a default constructor is
7491 // implicitly declared. An implicitly-declared default constructor
7492 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007493 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007494 "Should not build implicit default constructor!");
7495
Richard Smithafb49182012-11-29 01:34:07 +00007496 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7497 if (DSM.isAlreadyBeingDeclared())
7498 return 0;
7499
Richard Smith7756afa2012-06-10 05:43:50 +00007500 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7501 CXXDefaultConstructor,
7502 false);
7503
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007504 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007505 CanQualType ClassType
7506 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007507 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007508 DeclarationName Name
7509 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007510 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007511 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007512 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007513 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007514 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007515 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007516 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007517 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007518
7519 // Build an exception specification pointing back at this constructor.
7520 FunctionProtoType::ExtProtoInfo EPI;
7521 EPI.ExceptionSpecType = EST_Unevaluated;
7522 EPI.ExceptionSpecDecl = DefaultCon;
7523 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7524
Richard Smithbc2a35d2012-12-08 08:32:28 +00007525 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7526 // constructors is easy to compute.
7527 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7528
7529 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7530 DefaultCon->setDeletedAsWritten();
7531
Douglas Gregor18274032010-07-03 00:47:00 +00007532 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007533 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007534
Douglas Gregor23c94db2010-07-02 17:43:08 +00007535 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007536 PushOnScopeChains(DefaultCon, S, false);
7537 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007538
Douglas Gregor32df23e2010-07-01 22:02:46 +00007539 return DefaultCon;
7540}
7541
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007542void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7543 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007544 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007545 !Constructor->doesThisDeclarationHaveABody() &&
7546 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007547 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007548
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007549 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007550 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007551
Eli Friedman9a14db32012-10-18 20:14:08 +00007552 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007553 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007554 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007555 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007556 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007557 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007558 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007559 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007560 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007561
7562 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007563 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007564
7565 Constructor->setUsed();
7566 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007567
7568 if (ASTMutationListener *L = getASTMutationListener()) {
7569 L->CompletedImplicitDefinition(Constructor);
7570 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007571}
7572
Richard Smith7a614d82011-06-11 17:19:42 +00007573void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007574 // Check that any explicitly-defaulted methods have exception specifications
7575 // compatible with their implicit exception specifications.
7576 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007577}
7578
Sebastian Redlf677ea32011-02-05 19:23:19 +00007579void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7580 // We start with an initial pass over the base classes to collect those that
7581 // inherit constructors from. If there are none, we can forgo all further
7582 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007583 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007584 BasesVector BasesToInheritFrom;
7585 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7586 BaseE = ClassDecl->bases_end();
7587 BaseIt != BaseE; ++BaseIt) {
7588 if (BaseIt->getInheritConstructors()) {
7589 QualType Base = BaseIt->getType();
7590 if (Base->isDependentType()) {
7591 // If we inherit constructors from anything that is dependent, just
7592 // abort processing altogether. We'll get another chance for the
7593 // instantiations.
7594 return;
7595 }
7596 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7597 }
7598 }
7599 if (BasesToInheritFrom.empty())
7600 return;
7601
7602 // Now collect the constructors that we already have in the current class.
7603 // Those take precedence over inherited constructors.
7604 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7605 // unless there is a user-declared constructor with the same signature in
7606 // the class where the using-declaration appears.
7607 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7608 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7609 CtorE = ClassDecl->ctor_end();
7610 CtorIt != CtorE; ++CtorIt) {
7611 ExistingConstructors.insert(
7612 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7613 }
7614
Sebastian Redlf677ea32011-02-05 19:23:19 +00007615 DeclarationName CreatedCtorName =
7616 Context.DeclarationNames.getCXXConstructorName(
7617 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7618
7619 // Now comes the true work.
7620 // First, we keep a map from constructor types to the base that introduced
7621 // them. Needed for finding conflicting constructors. We also keep the
7622 // actually inserted declarations in there, for pretty diagnostics.
7623 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7624 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7625 ConstructorToSourceMap InheritedConstructors;
7626 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7627 BaseE = BasesToInheritFrom.end();
7628 BaseIt != BaseE; ++BaseIt) {
7629 const RecordType *Base = *BaseIt;
7630 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7631 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7632 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7633 CtorE = BaseDecl->ctor_end();
7634 CtorIt != CtorE; ++CtorIt) {
7635 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007636 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007637 DeclarationName Name =
7638 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007639 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7640 LookupQualifiedName(Result, CurContext);
7641 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007642 SourceLocation UsingLoc = UD ? UD->getLocation() :
7643 ClassDecl->getLocation();
7644
7645 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7646 // from the class X named in the using-declaration consists of actual
7647 // constructors and notional constructors that result from the
7648 // transformation of defaulted parameters as follows:
7649 // - all non-template default constructors of X, and
7650 // - for each non-template constructor of X that has at least one
7651 // parameter with a default argument, the set of constructors that
7652 // results from omitting any ellipsis parameter specification and
7653 // successively omitting parameters with a default argument from the
7654 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007655 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007656 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7657 const FunctionProtoType *BaseCtorType =
7658 BaseCtor->getType()->getAs<FunctionProtoType>();
7659
7660 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7661 maxParams = BaseCtor->getNumParams();
7662 params <= maxParams; ++params) {
7663 // Skip default constructors. They're never inherited.
7664 if (params == 0)
7665 continue;
7666 // Skip copy and move constructors for the same reason.
7667 if (CanBeCopyOrMove && params == 1)
7668 continue;
7669
7670 // Build up a function type for this particular constructor.
7671 // FIXME: The working paper does not consider that the exception spec
7672 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007673 // source. This code doesn't yet, either. When it does, this code will
7674 // need to be delayed until after exception specifications and in-class
7675 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007676 const Type *NewCtorType;
7677 if (params == maxParams)
7678 NewCtorType = BaseCtorType;
7679 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007680 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007681 for (unsigned i = 0; i < params; ++i) {
7682 Args.push_back(BaseCtorType->getArgType(i));
7683 }
7684 FunctionProtoType::ExtProtoInfo ExtInfo =
7685 BaseCtorType->getExtProtoInfo();
7686 ExtInfo.Variadic = false;
7687 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7688 Args.data(), params, ExtInfo)
7689 .getTypePtr();
7690 }
7691 const Type *CanonicalNewCtorType =
7692 Context.getCanonicalType(NewCtorType);
7693
7694 // Now that we have the type, first check if the class already has a
7695 // constructor with this signature.
7696 if (ExistingConstructors.count(CanonicalNewCtorType))
7697 continue;
7698
7699 // Then we check if we have already declared an inherited constructor
7700 // with this signature.
7701 std::pair<ConstructorToSourceMap::iterator, bool> result =
7702 InheritedConstructors.insert(std::make_pair(
7703 CanonicalNewCtorType,
7704 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7705 if (!result.second) {
7706 // Already in the map. If it came from a different class, that's an
7707 // error. Not if it's from the same.
7708 CanQualType PreviousBase = result.first->second.first;
7709 if (CanonicalBase != PreviousBase) {
7710 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7711 const CXXConstructorDecl *PrevBaseCtor =
7712 PrevCtor->getInheritedConstructor();
7713 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7714
7715 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7716 Diag(BaseCtor->getLocation(),
7717 diag::note_using_decl_constructor_conflict_current_ctor);
7718 Diag(PrevBaseCtor->getLocation(),
7719 diag::note_using_decl_constructor_conflict_previous_ctor);
7720 Diag(PrevCtor->getLocation(),
7721 diag::note_using_decl_constructor_conflict_previous_using);
7722 }
7723 continue;
7724 }
7725
7726 // OK, we're there, now add the constructor.
7727 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007728 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007729 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7730 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007731 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7732 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007733 /*ImplicitlyDeclared=*/true,
7734 // FIXME: Due to a defect in the standard, we treat inherited
7735 // constructors as constexpr even if that makes them ill-formed.
7736 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007737 NewCtor->setAccess(BaseCtor->getAccess());
7738
7739 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007740 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007741 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007742 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7743 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007744 /*IdentifierInfo=*/0,
7745 BaseCtorType->getArgType(i),
7746 /*TInfo=*/0, SC_None,
7747 SC_None, /*DefaultArg=*/0));
7748 }
David Blaikie4278c652011-09-21 18:16:56 +00007749 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007750 NewCtor->setInheritedConstructor(BaseCtor);
7751
Sebastian Redlf677ea32011-02-05 19:23:19 +00007752 ClassDecl->addDecl(NewCtor);
7753 result.first->second.second = NewCtor;
7754 }
7755 }
7756 }
7757}
7758
Sean Huntcb45a0f2011-05-12 22:46:25 +00007759Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007760Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7761 CXXRecordDecl *ClassDecl = MD->getParent();
7762
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007763 // C++ [except.spec]p14:
7764 // An implicitly declared special member function (Clause 12) shall have
7765 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007766 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007767 if (ClassDecl->isInvalidDecl())
7768 return ExceptSpec;
7769
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007770 // Direct base-class destructors.
7771 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7772 BEnd = ClassDecl->bases_end();
7773 B != BEnd; ++B) {
7774 if (B->isVirtual()) // Handled below.
7775 continue;
7776
7777 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007778 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007779 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007780 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007781
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007782 // Virtual base-class destructors.
7783 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7784 BEnd = ClassDecl->vbases_end();
7785 B != BEnd; ++B) {
7786 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007787 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007788 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007789 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007790
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007791 // Field destructors.
7792 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7793 FEnd = ClassDecl->field_end();
7794 F != FEnd; ++F) {
7795 if (const RecordType *RecordTy
7796 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007797 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007798 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007799 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007800
Sean Huntcb45a0f2011-05-12 22:46:25 +00007801 return ExceptSpec;
7802}
7803
7804CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7805 // C++ [class.dtor]p2:
7806 // If a class has no user-declared destructor, a destructor is
7807 // declared implicitly. An implicitly-declared destructor is an
7808 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007809 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007810
Richard Smithafb49182012-11-29 01:34:07 +00007811 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7812 if (DSM.isAlreadyBeingDeclared())
7813 return 0;
7814
Douglas Gregor4923aa22010-07-02 20:37:36 +00007815 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007816 CanQualType ClassType
7817 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007818 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007819 DeclarationName Name
7820 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007821 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007822 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007823 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7824 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007825 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007826 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007827 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007828 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007829
7830 // Build an exception specification pointing back at this destructor.
7831 FunctionProtoType::ExtProtoInfo EPI;
7832 EPI.ExceptionSpecType = EST_Unevaluated;
7833 EPI.ExceptionSpecDecl = Destructor;
7834 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7835
Richard Smithbc2a35d2012-12-08 08:32:28 +00007836 AddOverriddenMethods(ClassDecl, Destructor);
7837
7838 // We don't need to use SpecialMemberIsTrivial here; triviality for
7839 // destructors is easy to compute.
7840 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7841
7842 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7843 Destructor->setDeletedAsWritten();
7844
Douglas Gregor4923aa22010-07-02 20:37:36 +00007845 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007846 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007847
Douglas Gregor4923aa22010-07-02 20:37:36 +00007848 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007849 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007850 PushOnScopeChains(Destructor, S, false);
7851 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007852
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007853 return Destructor;
7854}
7855
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007856void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007857 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007858 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007859 !Destructor->doesThisDeclarationHaveABody() &&
7860 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007861 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007862 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007863 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007864
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007865 if (Destructor->isInvalidDecl())
7866 return;
7867
Eli Friedman9a14db32012-10-18 20:14:08 +00007868 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007869
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007870 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007871 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7872 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007873
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007874 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007875 Diag(CurrentLocation, diag::note_member_synthesized_at)
7876 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7877
7878 Destructor->setInvalidDecl();
7879 return;
7880 }
7881
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007882 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007883 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007884 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007885 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007886 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007887
7888 if (ASTMutationListener *L = getASTMutationListener()) {
7889 L->CompletedImplicitDefinition(Destructor);
7890 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007891}
7892
Richard Smitha4156b82012-04-21 18:42:51 +00007893/// \brief Perform any semantic analysis which needs to be delayed until all
7894/// pending class member declarations have been parsed.
7895void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00007896 // If the context is an invalid C++ class, just suppress these checks.
7897 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
7898 if (Record->isInvalidDecl()) {
7899 DelayedDestructorExceptionSpecChecks.clear();
7900 return;
7901 }
7902 }
7903
Richard Smitha4156b82012-04-21 18:42:51 +00007904 // Perform any deferred checking of exception specifications for virtual
7905 // destructors.
7906 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7907 i != e; ++i) {
7908 const CXXDestructorDecl *Dtor =
7909 DelayedDestructorExceptionSpecChecks[i].first;
7910 assert(!Dtor->getParent()->isDependentType() &&
7911 "Should not ever add destructors of templates into the list.");
7912 CheckOverridingFunctionExceptionSpec(Dtor,
7913 DelayedDestructorExceptionSpecChecks[i].second);
7914 }
7915 DelayedDestructorExceptionSpecChecks.clear();
7916}
7917
Richard Smithb9d0b762012-07-27 04:22:15 +00007918void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7919 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007920 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007921 "adjusting dtor exception specs was introduced in c++11");
7922
Sebastian Redl0ee33912011-05-19 05:13:44 +00007923 // C++11 [class.dtor]p3:
7924 // A declaration of a destructor that does not have an exception-
7925 // specification is implicitly considered to have the same exception-
7926 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007927 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007928 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007929 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007930 return;
7931
Chandler Carruth3f224b22011-09-20 04:55:26 +00007932 // Replace the destructor's type, building off the existing one. Fortunately,
7933 // the only thing of interest in the destructor type is its extended info.
7934 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007935 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7936 EPI.ExceptionSpecType = EST_Unevaluated;
7937 EPI.ExceptionSpecDecl = Destructor;
7938 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007939
Sebastian Redl0ee33912011-05-19 05:13:44 +00007940 // FIXME: If the destructor has a body that could throw, and the newly created
7941 // spec doesn't allow exceptions, we should emit a warning, because this
7942 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007943 // However, we don't have a body or an exception specification yet, so it
7944 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007945}
7946
Richard Smith8c889532012-11-14 00:50:40 +00007947/// When generating a defaulted copy or move assignment operator, if a field
7948/// should be copied with __builtin_memcpy rather than via explicit assignments,
7949/// do so. This optimization only applies for arrays of scalars, and for arrays
7950/// of class type where the selected copy/move-assignment operator is trivial.
7951static StmtResult
7952buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7953 Expr *To, Expr *From) {
7954 // Compute the size of the memory buffer to be copied.
7955 QualType SizeType = S.Context.getSizeType();
7956 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7957 S.Context.getTypeSizeInChars(T).getQuantity());
7958
7959 // Take the address of the field references for "from" and "to". We
7960 // directly construct UnaryOperators here because semantic analysis
7961 // does not permit us to take the address of an xvalue.
7962 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7963 S.Context.getPointerType(From->getType()),
7964 VK_RValue, OK_Ordinary, Loc);
7965 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7966 S.Context.getPointerType(To->getType()),
7967 VK_RValue, OK_Ordinary, Loc);
7968
7969 const Type *E = T->getBaseElementTypeUnsafe();
7970 bool NeedsCollectableMemCpy =
7971 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7972
7973 // Create a reference to the __builtin_objc_memmove_collectable function
7974 StringRef MemCpyName = NeedsCollectableMemCpy ?
7975 "__builtin_objc_memmove_collectable" :
7976 "__builtin_memcpy";
7977 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7978 Sema::LookupOrdinaryName);
7979 S.LookupName(R, S.TUScope, true);
7980
7981 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7982 if (!MemCpy)
7983 // Something went horribly wrong earlier, and we will have complained
7984 // about it.
7985 return StmtError();
7986
7987 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7988 VK_RValue, Loc, 0);
7989 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7990
7991 Expr *CallArgs[] = {
7992 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7993 };
7994 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7995 Loc, CallArgs, Loc);
7996
7997 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7998 return S.Owned(Call.takeAs<Stmt>());
7999}
8000
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008001/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008002/// \c To.
8003///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008004/// This routine is used to copy/move the members of a class with an
8005/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008006/// copied are arrays, this routine builds for loops to copy them.
8007///
8008/// \param S The Sema object used for type-checking.
8009///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008010/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008011///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008012/// \param T The type of the expressions being copied/moved. Both expressions
8013/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008014///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008015/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008016///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008017/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008018///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008019/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008020/// Otherwise, it's a non-static member subobject.
8021///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008022/// \param Copying Whether we're copying or moving.
8023///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008024/// \param Depth Internal parameter recording the depth of the recursion.
8025///
Richard Smith8c889532012-11-14 00:50:40 +00008026/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8027/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008028static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008029buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8030 Expr *To, Expr *From,
8031 bool CopyingBaseSubobject, bool Copying,
8032 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008033 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008034 // Each subobject is assigned in the manner appropriate to its type:
8035 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008036 // - if the subobject is of class type, as if by a call to operator= with
8037 // the subobject as the object expression and the corresponding
8038 // subobject of x as a single function argument (as if by explicit
8039 // qualification; that is, ignoring any possible virtual overriding
8040 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008041 //
8042 // C++03 [class.copy]p13:
8043 // - if the subobject is of class type, the copy assignment operator for
8044 // the class is used (as if by explicit qualification; that is,
8045 // ignoring any possible virtual overriding functions in more derived
8046 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008047 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8048 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008049
Douglas Gregor06a9f362010-05-01 20:49:11 +00008050 // Look for operator=.
8051 DeclarationName Name
8052 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8053 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8054 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008055
Richard Smith044c8aa2012-11-13 00:54:12 +00008056 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8057 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008058 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008059 LookupResult::Filter F = OpLookup.makeFilter();
8060 while (F.hasNext()) {
8061 NamedDecl *D = F.next();
8062 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8063 if (Method->isCopyAssignmentOperator() ||
8064 (!Copying && Method->isMoveAssignmentOperator()))
8065 continue;
8066
8067 F.erase();
8068 }
8069 F.done();
John McCallb0207482010-03-16 06:11:48 +00008070 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008071
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008072 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008073 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008074 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008075 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008076 // ambiguities), we need to cast "this" to that subobject type; to
8077 // ensure that we don't go through the virtual call mechanism, we need
8078 // to qualify the operator= name with the base class (see below). However,
8079 // this means that if the base class has a protected copy assignment
8080 // operator, the protected member access check will fail. So, we
8081 // rewrite "protected" access to "public" access in this case, since we
8082 // know by construction that we're calling from a derived class.
8083 if (CopyingBaseSubobject) {
8084 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8085 L != LEnd; ++L) {
8086 if (L.getAccess() == AS_protected)
8087 L.setAccess(AS_public);
8088 }
8089 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008090
Douglas Gregor06a9f362010-05-01 20:49:11 +00008091 // Create the nested-name-specifier that will be used to qualify the
8092 // reference to operator=; this is required to suppress the virtual
8093 // call mechanism.
8094 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008095 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008096 SS.MakeTrivial(S.Context,
8097 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008098 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008099 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008100
Douglas Gregor06a9f362010-05-01 20:49:11 +00008101 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008102 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008103 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008104 /*TemplateKWLoc=*/SourceLocation(),
8105 /*FirstQualifierInScope=*/0,
8106 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008107 /*TemplateArgs=*/0,
8108 /*SuppressQualifierCheck=*/true);
8109 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008110 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008111
Douglas Gregor06a9f362010-05-01 20:49:11 +00008112 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008113
Richard Smith044c8aa2012-11-13 00:54:12 +00008114 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008115 OpEqualRef.takeAs<Expr>(),
8116 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008117 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008118 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008119
Richard Smith8c889532012-11-14 00:50:40 +00008120 // If we built a call to a trivial 'operator=' while copying an array,
8121 // bail out. We'll replace the whole shebang with a memcpy.
8122 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8123 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8124 return StmtResult((Stmt*)0);
8125
Richard Smith044c8aa2012-11-13 00:54:12 +00008126 // Convert to an expression-statement, and clean up any produced
8127 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008128 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008129 }
John McCallb0207482010-03-16 06:11:48 +00008130
Richard Smith044c8aa2012-11-13 00:54:12 +00008131 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008132 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008133 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008134 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008135 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008136 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008137 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008138 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008139 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008140
8141 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008142 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008143
Douglas Gregor06a9f362010-05-01 20:49:11 +00008144 // Construct a loop over the array bounds, e.g.,
8145 //
8146 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8147 //
8148 // that will copy each of the array elements.
8149 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008150
Douglas Gregor06a9f362010-05-01 20:49:11 +00008151 // Create the iteration variable.
8152 IdentifierInfo *IterationVarName = 0;
8153 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008154 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008155 llvm::raw_svector_ostream OS(Str);
8156 OS << "__i" << Depth;
8157 IterationVarName = &S.Context.Idents.get(OS.str());
8158 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008159 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008160 IterationVarName, SizeType,
8161 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008162 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008163
Douglas Gregor06a9f362010-05-01 20:49:11 +00008164 // Initialize the iteration variable to zero.
8165 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008166 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008167
8168 // Create a reference to the iteration variable; we'll use this several
8169 // times throughout.
8170 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008171 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008172 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008173 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8174 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8175
Douglas Gregor06a9f362010-05-01 20:49:11 +00008176 // Create the DeclStmt that holds the iteration variable.
8177 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008178
Douglas Gregor06a9f362010-05-01 20:49:11 +00008179 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008180 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008181 IterationVarRefRVal,
8182 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008183 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008184 IterationVarRefRVal,
8185 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008186 if (!Copying) // Cast to rvalue
8187 From = CastForMoving(S, From);
8188
8189 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008190 StmtResult Copy =
8191 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8192 To, From, CopyingBaseSubobject,
8193 Copying, Depth + 1);
8194 // Bail out if copying fails or if we determined that we should use memcpy.
8195 if (Copy.isInvalid() || !Copy.get())
8196 return Copy;
8197
8198 // Create the comparison against the array bound.
8199 llvm::APInt Upper
8200 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8201 Expr *Comparison
8202 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8203 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8204 BO_NE, S.Context.BoolTy,
8205 VK_RValue, OK_Ordinary, Loc, false);
8206
8207 // Create the pre-increment of the iteration variable.
8208 Expr *Increment
8209 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8210 VK_LValue, OK_Ordinary, Loc);
8211
Douglas Gregor06a9f362010-05-01 20:49:11 +00008212 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008213 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008214 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008215 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008216 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008217}
8218
Richard Smith8c889532012-11-14 00:50:40 +00008219static StmtResult
8220buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8221 Expr *To, Expr *From,
8222 bool CopyingBaseSubobject, bool Copying) {
8223 // Maybe we should use a memcpy?
8224 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8225 T.isTriviallyCopyableType(S.Context))
8226 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8227
8228 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8229 CopyingBaseSubobject,
8230 Copying, 0));
8231
8232 // If we ended up picking a trivial assignment operator for an array of a
8233 // non-trivially-copyable class type, just emit a memcpy.
8234 if (!Result.isInvalid() && !Result.get())
8235 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8236
8237 return Result;
8238}
8239
Richard Smithb9d0b762012-07-27 04:22:15 +00008240Sema::ImplicitExceptionSpecification
8241Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8242 CXXRecordDecl *ClassDecl = MD->getParent();
8243
8244 ImplicitExceptionSpecification ExceptSpec(*this);
8245 if (ClassDecl->isInvalidDecl())
8246 return ExceptSpec;
8247
8248 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8249 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8250 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8251
Douglas Gregorb87786f2010-07-01 17:48:08 +00008252 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008253 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008254 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008255
8256 // It is unspecified whether or not an implicit copy assignment operator
8257 // attempts to deduplicate calls to assignment operators of virtual bases are
8258 // made. As such, this exception specification is effectively unspecified.
8259 // Based on a similar decision made for constness in C++0x, we're erring on
8260 // the side of assuming such calls to be made regardless of whether they
8261 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008262 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8263 BaseEnd = ClassDecl->bases_end();
8264 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008265 if (Base->isVirtual())
8266 continue;
8267
Douglas Gregora376d102010-07-02 21:50:04 +00008268 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008269 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008270 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8271 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008272 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008273 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008274
8275 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8276 BaseEnd = ClassDecl->vbases_end();
8277 Base != BaseEnd; ++Base) {
8278 CXXRecordDecl *BaseClassDecl
8279 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8280 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8281 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008282 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008283 }
8284
Douglas Gregorb87786f2010-07-01 17:48:08 +00008285 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8286 FieldEnd = ClassDecl->field_end();
8287 Field != FieldEnd;
8288 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008289 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008290 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8291 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008292 LookupCopyingAssignment(FieldClassDecl,
8293 ArgQuals | FieldType.getCVRQualifiers(),
8294 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008295 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008296 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008297 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008298
Richard Smithb9d0b762012-07-27 04:22:15 +00008299 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008300}
8301
8302CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8303 // Note: The following rules are largely analoguous to the copy
8304 // constructor rules. Note that virtual bases are not taken into account
8305 // for determining the argument type of the operator. Note also that
8306 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008307 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008308
Richard Smithafb49182012-11-29 01:34:07 +00008309 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8310 if (DSM.isAlreadyBeingDeclared())
8311 return 0;
8312
Sean Hunt30de05c2011-05-14 05:23:20 +00008313 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8314 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008315 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008316 ArgType = ArgType.withConst();
8317 ArgType = Context.getLValueReferenceType(ArgType);
8318
Douglas Gregord3c35902010-07-01 16:36:15 +00008319 // An implicitly-declared copy assignment operator is an inline public
8320 // member of its class.
8321 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008322 SourceLocation ClassLoc = ClassDecl->getLocation();
8323 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008324 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008325 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008326 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008327 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008328 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008329 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008330 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008331 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008332 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008333
8334 // Build an exception specification pointing back at this member.
8335 FunctionProtoType::ExtProtoInfo EPI;
8336 EPI.ExceptionSpecType = EST_Unevaluated;
8337 EPI.ExceptionSpecDecl = CopyAssignment;
8338 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8339
Douglas Gregord3c35902010-07-01 16:36:15 +00008340 // Add the parameter to the operator.
8341 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008342 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008343 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008344 SC_None,
8345 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008346 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008347
Richard Smithbc2a35d2012-12-08 08:32:28 +00008348 AddOverriddenMethods(ClassDecl, CopyAssignment);
8349
8350 CopyAssignment->setTrivial(
8351 ClassDecl->needsOverloadResolutionForCopyAssignment()
8352 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8353 : ClassDecl->hasTrivialCopyAssignment());
8354
Nico Weberafcc96a2012-01-23 03:19:29 +00008355 // C++0x [class.copy]p19:
8356 // .... If the class definition does not explicitly declare a copy
8357 // assignment operator, there is no user-declared move constructor, and
8358 // there is no user-declared move assignment operator, a copy assignment
8359 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008360 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008361 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008362
Richard Smithbc2a35d2012-12-08 08:32:28 +00008363 // Note that we have added this copy-assignment operator.
8364 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8365
8366 if (Scope *S = getScopeForContext(ClassDecl))
8367 PushOnScopeChains(CopyAssignment, S, false);
8368 ClassDecl->addDecl(CopyAssignment);
8369
Douglas Gregord3c35902010-07-01 16:36:15 +00008370 return CopyAssignment;
8371}
8372
Douglas Gregor06a9f362010-05-01 20:49:11 +00008373void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8374 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008375 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008376 CopyAssignOperator->isOverloadedOperator() &&
8377 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008378 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8379 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008380 "DefineImplicitCopyAssignment called for wrong function");
8381
8382 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8383
8384 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8385 CopyAssignOperator->setInvalidDecl();
8386 return;
8387 }
8388
8389 CopyAssignOperator->setUsed();
8390
Eli Friedman9a14db32012-10-18 20:14:08 +00008391 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008392 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008393
8394 // C++0x [class.copy]p30:
8395 // The implicitly-defined or explicitly-defaulted copy assignment operator
8396 // for a non-union class X performs memberwise copy assignment of its
8397 // subobjects. The direct base classes of X are assigned first, in the
8398 // order of their declaration in the base-specifier-list, and then the
8399 // immediate non-static data members of X are assigned, in the order in
8400 // which they were declared in the class definition.
8401
8402 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008403 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008404
8405 // The parameter for the "other" object, which we are copying from.
8406 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8407 Qualifiers OtherQuals = Other->getType().getQualifiers();
8408 QualType OtherRefType = Other->getType();
8409 if (const LValueReferenceType *OtherRef
8410 = OtherRefType->getAs<LValueReferenceType>()) {
8411 OtherRefType = OtherRef->getPointeeType();
8412 OtherQuals = OtherRefType.getQualifiers();
8413 }
8414
8415 // Our location for everything implicitly-generated.
8416 SourceLocation Loc = CopyAssignOperator->getLocation();
8417
8418 // Construct a reference to the "other" object. We'll be using this
8419 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008420 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008421 assert(OtherRef && "Reference to parameter cannot fail!");
8422
8423 // Construct the "this" pointer. We'll be using this throughout the generated
8424 // ASTs.
8425 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8426 assert(This && "Reference to this cannot fail!");
8427
8428 // Assign base classes.
8429 bool Invalid = false;
8430 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8431 E = ClassDecl->bases_end(); Base != E; ++Base) {
8432 // Form the assignment:
8433 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8434 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008435 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008436 Invalid = true;
8437 continue;
8438 }
8439
John McCallf871d0c2010-08-07 06:22:56 +00008440 CXXCastPath BasePath;
8441 BasePath.push_back(Base);
8442
Douglas Gregor06a9f362010-05-01 20:49:11 +00008443 // Construct the "from" expression, which is an implicit cast to the
8444 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008445 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008446 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8447 CK_UncheckedDerivedToBase,
8448 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008449
8450 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008451 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008452
8453 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008454 To = ImpCastExprToType(To.take(),
8455 Context.getCVRQualifiedType(BaseType,
8456 CopyAssignOperator->getTypeQualifiers()),
8457 CK_UncheckedDerivedToBase,
8458 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008459
8460 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008461 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008462 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008463 /*CopyingBaseSubobject=*/true,
8464 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008465 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008466 Diag(CurrentLocation, diag::note_member_synthesized_at)
8467 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8468 CopyAssignOperator->setInvalidDecl();
8469 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008470 }
8471
8472 // Success! Record the copy.
8473 Statements.push_back(Copy.takeAs<Expr>());
8474 }
8475
Douglas Gregor06a9f362010-05-01 20:49:11 +00008476 // Assign non-static members.
8477 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8478 FieldEnd = ClassDecl->field_end();
8479 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008480 if (Field->isUnnamedBitfield())
8481 continue;
8482
Douglas Gregor06a9f362010-05-01 20:49:11 +00008483 // Check for members of reference type; we can't copy those.
8484 if (Field->getType()->isReferenceType()) {
8485 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8486 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8487 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008488 Diag(CurrentLocation, diag::note_member_synthesized_at)
8489 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008490 Invalid = true;
8491 continue;
8492 }
8493
8494 // Check for members of const-qualified, non-class type.
8495 QualType BaseType = Context.getBaseElementType(Field->getType());
8496 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8497 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8498 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8499 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008500 Diag(CurrentLocation, diag::note_member_synthesized_at)
8501 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008502 Invalid = true;
8503 continue;
8504 }
John McCallb77115d2011-06-17 00:18:42 +00008505
8506 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008507 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8508 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008509
8510 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008511 if (FieldType->isIncompleteArrayType()) {
8512 assert(ClassDecl->hasFlexibleArrayMember() &&
8513 "Incomplete array type is not valid");
8514 continue;
8515 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008516
8517 // Build references to the field in the object we're copying from and to.
8518 CXXScopeSpec SS; // Intentionally empty
8519 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8520 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008521 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008522 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008523 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008524 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008525 SS, SourceLocation(), 0,
8526 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008527 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008528 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008529 SS, SourceLocation(), 0,
8530 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008531 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8532 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008533
Douglas Gregor06a9f362010-05-01 20:49:11 +00008534 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008535 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008536 To.get(), From.get(),
8537 /*CopyingBaseSubobject=*/false,
8538 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008539 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008540 Diag(CurrentLocation, diag::note_member_synthesized_at)
8541 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8542 CopyAssignOperator->setInvalidDecl();
8543 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008544 }
8545
8546 // Success! Record the copy.
8547 Statements.push_back(Copy.takeAs<Stmt>());
8548 }
8549
8550 if (!Invalid) {
8551 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008552 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008553
John McCall60d7b3a2010-08-24 06:29:42 +00008554 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008555 if (Return.isInvalid())
8556 Invalid = true;
8557 else {
8558 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008559
8560 if (Trap.hasErrorOccurred()) {
8561 Diag(CurrentLocation, diag::note_member_synthesized_at)
8562 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8563 Invalid = true;
8564 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008565 }
8566 }
8567
8568 if (Invalid) {
8569 CopyAssignOperator->setInvalidDecl();
8570 return;
8571 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008572
8573 StmtResult Body;
8574 {
8575 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008576 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008577 /*isStmtExpr=*/false);
8578 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8579 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008580 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008581
8582 if (ASTMutationListener *L = getASTMutationListener()) {
8583 L->CompletedImplicitDefinition(CopyAssignOperator);
8584 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008585}
8586
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008587Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008588Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8589 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008590
Richard Smithb9d0b762012-07-27 04:22:15 +00008591 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008592 if (ClassDecl->isInvalidDecl())
8593 return ExceptSpec;
8594
8595 // C++0x [except.spec]p14:
8596 // An implicitly declared special member function (Clause 12) shall have an
8597 // exception-specification. [...]
8598
8599 // It is unspecified whether or not an implicit move assignment operator
8600 // attempts to deduplicate calls to assignment operators of virtual bases are
8601 // made. As such, this exception specification is effectively unspecified.
8602 // Based on a similar decision made for constness in C++0x, we're erring on
8603 // the side of assuming such calls to be made regardless of whether they
8604 // actually happen.
8605 // Note that a move constructor is not implicitly declared when there are
8606 // virtual bases, but it can still be user-declared and explicitly defaulted.
8607 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8608 BaseEnd = ClassDecl->bases_end();
8609 Base != BaseEnd; ++Base) {
8610 if (Base->isVirtual())
8611 continue;
8612
8613 CXXRecordDecl *BaseClassDecl
8614 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8615 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008616 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008617 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008618 }
8619
8620 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8621 BaseEnd = ClassDecl->vbases_end();
8622 Base != BaseEnd; ++Base) {
8623 CXXRecordDecl *BaseClassDecl
8624 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8625 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008626 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008627 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008628 }
8629
8630 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8631 FieldEnd = ClassDecl->field_end();
8632 Field != FieldEnd;
8633 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008634 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008635 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008636 if (CXXMethodDecl *MoveAssign =
8637 LookupMovingAssignment(FieldClassDecl,
8638 FieldType.getCVRQualifiers(),
8639 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008640 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008641 }
8642 }
8643
8644 return ExceptSpec;
8645}
8646
Richard Smith1c931be2012-04-02 18:40:40 +00008647/// Determine whether the class type has any direct or indirect virtual base
8648/// classes which have a non-trivial move assignment operator.
8649static bool
8650hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8651 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8652 BaseEnd = ClassDecl->vbases_end();
8653 Base != BaseEnd; ++Base) {
8654 CXXRecordDecl *BaseClass =
8655 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8656
8657 // Try to declare the move assignment. If it would be deleted, then the
8658 // class does not have a non-trivial move assignment.
8659 if (BaseClass->needsImplicitMoveAssignment())
8660 S.DeclareImplicitMoveAssignment(BaseClass);
8661
Richard Smith426391c2012-11-16 00:53:38 +00008662 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008663 return true;
8664 }
8665
8666 return false;
8667}
8668
8669/// Determine whether the given type either has a move constructor or is
8670/// trivially copyable.
8671static bool
8672hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8673 Type = S.Context.getBaseElementType(Type);
8674
8675 // FIXME: Technically, non-trivially-copyable non-class types, such as
8676 // reference types, are supposed to return false here, but that appears
8677 // to be a standard defect.
8678 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008679 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008680 return true;
8681
8682 if (Type.isTriviallyCopyableType(S.Context))
8683 return true;
8684
8685 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008686 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8687 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008688 if (ClassDecl->needsImplicitMoveConstructor())
8689 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008690 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008691 }
8692
Richard Smithe5411b72012-12-01 02:35:44 +00008693 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8694 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008695 if (ClassDecl->needsImplicitMoveAssignment())
8696 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008697 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008698}
8699
8700/// Determine whether all non-static data members and direct or virtual bases
8701/// of class \p ClassDecl have either a move operation, or are trivially
8702/// copyable.
8703static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8704 bool IsConstructor) {
8705 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8706 BaseEnd = ClassDecl->bases_end();
8707 Base != BaseEnd; ++Base) {
8708 if (Base->isVirtual())
8709 continue;
8710
8711 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8712 return false;
8713 }
8714
8715 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8716 BaseEnd = ClassDecl->vbases_end();
8717 Base != BaseEnd; ++Base) {
8718 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8719 return false;
8720 }
8721
8722 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8723 FieldEnd = ClassDecl->field_end();
8724 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008725 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008726 return false;
8727 }
8728
8729 return true;
8730}
8731
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008732CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008733 // C++11 [class.copy]p20:
8734 // If the definition of a class X does not explicitly declare a move
8735 // assignment operator, one will be implicitly declared as defaulted
8736 // if and only if:
8737 //
8738 // - [first 4 bullets]
8739 assert(ClassDecl->needsImplicitMoveAssignment());
8740
Richard Smithafb49182012-11-29 01:34:07 +00008741 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8742 if (DSM.isAlreadyBeingDeclared())
8743 return 0;
8744
Richard Smith1c931be2012-04-02 18:40:40 +00008745 // [Checked after we build the declaration]
8746 // - the move assignment operator would not be implicitly defined as
8747 // deleted,
8748
8749 // [DR1402]:
8750 // - X has no direct or indirect virtual base class with a non-trivial
8751 // move assignment operator, and
8752 // - each of X's non-static data members and direct or virtual base classes
8753 // has a type that either has a move assignment operator or is trivially
8754 // copyable.
8755 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8756 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8757 ClassDecl->setFailedImplicitMoveAssignment();
8758 return 0;
8759 }
8760
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008761 // Note: The following rules are largely analoguous to the move
8762 // constructor rules.
8763
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008764 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8765 QualType RetType = Context.getLValueReferenceType(ArgType);
8766 ArgType = Context.getRValueReferenceType(ArgType);
8767
8768 // An implicitly-declared move assignment operator is an inline public
8769 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008770 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8771 SourceLocation ClassLoc = ClassDecl->getLocation();
8772 DeclarationNameInfo NameInfo(Name, ClassLoc);
8773 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008774 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008775 /*TInfo=*/0, /*isStatic=*/false,
8776 /*StorageClassAsWritten=*/SC_None,
8777 /*isInline=*/true,
8778 /*isConstexpr=*/false,
8779 SourceLocation());
8780 MoveAssignment->setAccess(AS_public);
8781 MoveAssignment->setDefaulted();
8782 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008783
Richard Smithb9d0b762012-07-27 04:22:15 +00008784 // Build an exception specification pointing back at this member.
8785 FunctionProtoType::ExtProtoInfo EPI;
8786 EPI.ExceptionSpecType = EST_Unevaluated;
8787 EPI.ExceptionSpecDecl = MoveAssignment;
8788 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8789
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008790 // Add the parameter to the operator.
8791 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8792 ClassLoc, ClassLoc, /*Id=*/0,
8793 ArgType, /*TInfo=*/0,
8794 SC_None,
8795 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008796 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008797
Richard Smithbc2a35d2012-12-08 08:32:28 +00008798 AddOverriddenMethods(ClassDecl, MoveAssignment);
8799
8800 MoveAssignment->setTrivial(
8801 ClassDecl->needsOverloadResolutionForMoveAssignment()
8802 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8803 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008804
8805 // C++0x [class.copy]p9:
8806 // If the definition of a class X does not explicitly declare a move
8807 // assignment operator, one will be implicitly declared as defaulted if and
8808 // only if:
8809 // [...]
8810 // - the move assignment operator would not be implicitly defined as
8811 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008812 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008813 // Cache this result so that we don't try to generate this over and over
8814 // on every lookup, leaking memory and wasting time.
8815 ClassDecl->setFailedImplicitMoveAssignment();
8816 return 0;
8817 }
8818
Richard Smithbc2a35d2012-12-08 08:32:28 +00008819 // Note that we have added this copy-assignment operator.
8820 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8821
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008822 if (Scope *S = getScopeForContext(ClassDecl))
8823 PushOnScopeChains(MoveAssignment, S, false);
8824 ClassDecl->addDecl(MoveAssignment);
8825
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008826 return MoveAssignment;
8827}
8828
8829void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8830 CXXMethodDecl *MoveAssignOperator) {
8831 assert((MoveAssignOperator->isDefaulted() &&
8832 MoveAssignOperator->isOverloadedOperator() &&
8833 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008834 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8835 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008836 "DefineImplicitMoveAssignment called for wrong function");
8837
8838 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8839
8840 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8841 MoveAssignOperator->setInvalidDecl();
8842 return;
8843 }
8844
8845 MoveAssignOperator->setUsed();
8846
Eli Friedman9a14db32012-10-18 20:14:08 +00008847 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008848 DiagnosticErrorTrap Trap(Diags);
8849
8850 // C++0x [class.copy]p28:
8851 // The implicitly-defined or move assignment operator for a non-union class
8852 // X performs memberwise move assignment of its subobjects. The direct base
8853 // classes of X are assigned first, in the order of their declaration in the
8854 // base-specifier-list, and then the immediate non-static data members of X
8855 // are assigned, in the order in which they were declared in the class
8856 // definition.
8857
8858 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008859 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008860
8861 // The parameter for the "other" object, which we are move from.
8862 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8863 QualType OtherRefType = Other->getType()->
8864 getAs<RValueReferenceType>()->getPointeeType();
8865 assert(OtherRefType.getQualifiers() == 0 &&
8866 "Bad argument type of defaulted move assignment");
8867
8868 // Our location for everything implicitly-generated.
8869 SourceLocation Loc = MoveAssignOperator->getLocation();
8870
8871 // Construct a reference to the "other" object. We'll be using this
8872 // throughout the generated ASTs.
8873 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8874 assert(OtherRef && "Reference to parameter cannot fail!");
8875 // Cast to rvalue.
8876 OtherRef = CastForMoving(*this, OtherRef);
8877
8878 // Construct the "this" pointer. We'll be using this throughout the generated
8879 // ASTs.
8880 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8881 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008882
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008883 // Assign base classes.
8884 bool Invalid = false;
8885 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8886 E = ClassDecl->bases_end(); Base != E; ++Base) {
8887 // Form the assignment:
8888 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8889 QualType BaseType = Base->getType().getUnqualifiedType();
8890 if (!BaseType->isRecordType()) {
8891 Invalid = true;
8892 continue;
8893 }
8894
8895 CXXCastPath BasePath;
8896 BasePath.push_back(Base);
8897
8898 // Construct the "from" expression, which is an implicit cast to the
8899 // appropriately-qualified base type.
8900 Expr *From = OtherRef;
8901 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008902 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008903
8904 // Dereference "this".
8905 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8906
8907 // Implicitly cast "this" to the appropriately-qualified base type.
8908 To = ImpCastExprToType(To.take(),
8909 Context.getCVRQualifiedType(BaseType,
8910 MoveAssignOperator->getTypeQualifiers()),
8911 CK_UncheckedDerivedToBase,
8912 VK_LValue, &BasePath);
8913
8914 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008915 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008916 To.get(), From,
8917 /*CopyingBaseSubobject=*/true,
8918 /*Copying=*/false);
8919 if (Move.isInvalid()) {
8920 Diag(CurrentLocation, diag::note_member_synthesized_at)
8921 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8922 MoveAssignOperator->setInvalidDecl();
8923 return;
8924 }
8925
8926 // Success! Record the move.
8927 Statements.push_back(Move.takeAs<Expr>());
8928 }
8929
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008930 // Assign non-static members.
8931 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8932 FieldEnd = ClassDecl->field_end();
8933 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008934 if (Field->isUnnamedBitfield())
8935 continue;
8936
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008937 // Check for members of reference type; we can't move those.
8938 if (Field->getType()->isReferenceType()) {
8939 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8940 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8941 Diag(Field->getLocation(), diag::note_declared_at);
8942 Diag(CurrentLocation, diag::note_member_synthesized_at)
8943 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8944 Invalid = true;
8945 continue;
8946 }
8947
8948 // Check for members of const-qualified, non-class type.
8949 QualType BaseType = Context.getBaseElementType(Field->getType());
8950 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8951 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8952 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8953 Diag(Field->getLocation(), diag::note_declared_at);
8954 Diag(CurrentLocation, diag::note_member_synthesized_at)
8955 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8956 Invalid = true;
8957 continue;
8958 }
8959
8960 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008961 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8962 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008963
8964 QualType FieldType = Field->getType().getNonReferenceType();
8965 if (FieldType->isIncompleteArrayType()) {
8966 assert(ClassDecl->hasFlexibleArrayMember() &&
8967 "Incomplete array type is not valid");
8968 continue;
8969 }
8970
8971 // Build references to the field in the object we're copying from and to.
8972 CXXScopeSpec SS; // Intentionally empty
8973 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8974 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008975 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008976 MemberLookup.resolveKind();
8977 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8978 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008979 SS, SourceLocation(), 0,
8980 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008981 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8982 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008983 SS, SourceLocation(), 0,
8984 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008985 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8986 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8987
8988 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8989 "Member reference with rvalue base must be rvalue except for reference "
8990 "members, which aren't allowed for move assignment.");
8991
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008992 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008993 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008994 To.get(), From.get(),
8995 /*CopyingBaseSubobject=*/false,
8996 /*Copying=*/false);
8997 if (Move.isInvalid()) {
8998 Diag(CurrentLocation, diag::note_member_synthesized_at)
8999 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9000 MoveAssignOperator->setInvalidDecl();
9001 return;
9002 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009003
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009004 // Success! Record the copy.
9005 Statements.push_back(Move.takeAs<Stmt>());
9006 }
9007
9008 if (!Invalid) {
9009 // Add a "return *this;"
9010 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9011
9012 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9013 if (Return.isInvalid())
9014 Invalid = true;
9015 else {
9016 Statements.push_back(Return.takeAs<Stmt>());
9017
9018 if (Trap.hasErrorOccurred()) {
9019 Diag(CurrentLocation, diag::note_member_synthesized_at)
9020 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9021 Invalid = true;
9022 }
9023 }
9024 }
9025
9026 if (Invalid) {
9027 MoveAssignOperator->setInvalidDecl();
9028 return;
9029 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009030
9031 StmtResult Body;
9032 {
9033 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009034 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009035 /*isStmtExpr=*/false);
9036 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9037 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009038 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9039
9040 if (ASTMutationListener *L = getASTMutationListener()) {
9041 L->CompletedImplicitDefinition(MoveAssignOperator);
9042 }
9043}
9044
Richard Smithb9d0b762012-07-27 04:22:15 +00009045Sema::ImplicitExceptionSpecification
9046Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9047 CXXRecordDecl *ClassDecl = MD->getParent();
9048
9049 ImplicitExceptionSpecification ExceptSpec(*this);
9050 if (ClassDecl->isInvalidDecl())
9051 return ExceptSpec;
9052
9053 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9054 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9055 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9056
Douglas Gregor0d405db2010-07-01 20:59:04 +00009057 // C++ [except.spec]p14:
9058 // An implicitly declared special member function (Clause 12) shall have an
9059 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009060 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9061 BaseEnd = ClassDecl->bases_end();
9062 Base != BaseEnd;
9063 ++Base) {
9064 // Virtual bases are handled below.
9065 if (Base->isVirtual())
9066 continue;
9067
Douglas Gregor22584312010-07-02 23:41:54 +00009068 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009069 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009070 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009071 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009072 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009073 }
9074 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9075 BaseEnd = ClassDecl->vbases_end();
9076 Base != BaseEnd;
9077 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009078 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009079 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009080 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009081 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009082 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009083 }
9084 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9085 FieldEnd = ClassDecl->field_end();
9086 Field != FieldEnd;
9087 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009088 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009089 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9090 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009091 LookupCopyingConstructor(FieldClassDecl,
9092 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009093 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009094 }
9095 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009096
Richard Smithb9d0b762012-07-27 04:22:15 +00009097 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009098}
9099
9100CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9101 CXXRecordDecl *ClassDecl) {
9102 // C++ [class.copy]p4:
9103 // If the class definition does not explicitly declare a copy
9104 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009105 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009106
Richard Smithafb49182012-11-29 01:34:07 +00009107 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9108 if (DSM.isAlreadyBeingDeclared())
9109 return 0;
9110
Sean Hunt49634cf2011-05-13 06:10:58 +00009111 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9112 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009113 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009114 if (Const)
9115 ArgType = ArgType.withConst();
9116 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009117
Richard Smith7756afa2012-06-10 05:43:50 +00009118 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9119 CXXCopyConstructor,
9120 Const);
9121
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009122 DeclarationName Name
9123 = Context.DeclarationNames.getCXXConstructorName(
9124 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009125 SourceLocation ClassLoc = ClassDecl->getLocation();
9126 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009127
9128 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009129 // member of its class.
9130 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009131 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009132 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009133 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009134 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009135 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009136
Richard Smithb9d0b762012-07-27 04:22:15 +00009137 // Build an exception specification pointing back at this member.
9138 FunctionProtoType::ExtProtoInfo EPI;
9139 EPI.ExceptionSpecType = EST_Unevaluated;
9140 EPI.ExceptionSpecDecl = CopyConstructor;
9141 CopyConstructor->setType(
9142 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9143
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009144 // Add the parameter to the constructor.
9145 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009146 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009147 /*IdentifierInfo=*/0,
9148 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009149 SC_None,
9150 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009151 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009152
Richard Smithbc2a35d2012-12-08 08:32:28 +00009153 CopyConstructor->setTrivial(
9154 ClassDecl->needsOverloadResolutionForCopyConstructor()
9155 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9156 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009157
Nico Weberafcc96a2012-01-23 03:19:29 +00009158 // C++11 [class.copy]p8:
9159 // ... If the class definition does not explicitly declare a copy
9160 // constructor, there is no user-declared move constructor, and there is no
9161 // user-declared move assignment operator, a copy constructor is implicitly
9162 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009163 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009164 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009165
Richard Smithbc2a35d2012-12-08 08:32:28 +00009166 // Note that we have declared this constructor.
9167 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9168
9169 if (Scope *S = getScopeForContext(ClassDecl))
9170 PushOnScopeChains(CopyConstructor, S, false);
9171 ClassDecl->addDecl(CopyConstructor);
9172
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009173 return CopyConstructor;
9174}
9175
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009176void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009177 CXXConstructorDecl *CopyConstructor) {
9178 assert((CopyConstructor->isDefaulted() &&
9179 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009180 !CopyConstructor->doesThisDeclarationHaveABody() &&
9181 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009182 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009183
Anders Carlsson63010a72010-04-23 16:24:12 +00009184 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009185 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009186
Eli Friedman9a14db32012-10-18 20:14:08 +00009187 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009188 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009189
David Blaikie93c86172013-01-17 05:26:25 +00009190 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009191 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009192 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009193 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009194 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009195 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009196 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009197 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9198 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009199 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009200 /*isStmtExpr=*/false)
9201 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009202 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009203 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009204
9205 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009206 if (ASTMutationListener *L = getASTMutationListener()) {
9207 L->CompletedImplicitDefinition(CopyConstructor);
9208 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009209}
9210
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009211Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009212Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9213 CXXRecordDecl *ClassDecl = MD->getParent();
9214
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009215 // C++ [except.spec]p14:
9216 // An implicitly declared special member function (Clause 12) shall have an
9217 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009218 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009219 if (ClassDecl->isInvalidDecl())
9220 return ExceptSpec;
9221
9222 // Direct base-class constructors.
9223 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9224 BEnd = ClassDecl->bases_end();
9225 B != BEnd; ++B) {
9226 if (B->isVirtual()) // Handled below.
9227 continue;
9228
9229 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9230 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009231 CXXConstructorDecl *Constructor =
9232 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009233 // If this is a deleted function, add it anyway. This might be conformant
9234 // with the standard. This might not. I'm not sure. It might not matter.
9235 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009236 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009237 }
9238 }
9239
9240 // Virtual base-class constructors.
9241 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9242 BEnd = ClassDecl->vbases_end();
9243 B != BEnd; ++B) {
9244 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9245 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009246 CXXConstructorDecl *Constructor =
9247 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009248 // If this is a deleted function, add it anyway. This might be conformant
9249 // with the standard. This might not. I'm not sure. It might not matter.
9250 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009251 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009252 }
9253 }
9254
9255 // Field constructors.
9256 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9257 FEnd = ClassDecl->field_end();
9258 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009259 QualType FieldType = Context.getBaseElementType(F->getType());
9260 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9261 CXXConstructorDecl *Constructor =
9262 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009263 // If this is a deleted function, add it anyway. This might be conformant
9264 // with the standard. This might not. I'm not sure. It might not matter.
9265 // In particular, the problem is that this function never gets called. It
9266 // might just be ill-formed because this function attempts to refer to
9267 // a deleted function here.
9268 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009269 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009270 }
9271 }
9272
9273 return ExceptSpec;
9274}
9275
9276CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9277 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009278 // C++11 [class.copy]p9:
9279 // If the definition of a class X does not explicitly declare a move
9280 // constructor, one will be implicitly declared as defaulted if and only if:
9281 //
9282 // - [first 4 bullets]
9283 assert(ClassDecl->needsImplicitMoveConstructor());
9284
Richard Smithafb49182012-11-29 01:34:07 +00009285 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9286 if (DSM.isAlreadyBeingDeclared())
9287 return 0;
9288
Richard Smith1c931be2012-04-02 18:40:40 +00009289 // [Checked after we build the declaration]
9290 // - the move assignment operator would not be implicitly defined as
9291 // deleted,
9292
9293 // [DR1402]:
9294 // - each of X's non-static data members and direct or virtual base classes
9295 // has a type that either has a move constructor or is trivially copyable.
9296 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9297 ClassDecl->setFailedImplicitMoveConstructor();
9298 return 0;
9299 }
9300
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009301 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9302 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009303
Richard Smith7756afa2012-06-10 05:43:50 +00009304 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9305 CXXMoveConstructor,
9306 false);
9307
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009308 DeclarationName Name
9309 = Context.DeclarationNames.getCXXConstructorName(
9310 Context.getCanonicalType(ClassType));
9311 SourceLocation ClassLoc = ClassDecl->getLocation();
9312 DeclarationNameInfo NameInfo(Name, ClassLoc);
9313
9314 // C++0x [class.copy]p11:
9315 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009316 // member of its class.
9317 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009318 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009319 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009320 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009321 MoveConstructor->setAccess(AS_public);
9322 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009323
Richard Smithb9d0b762012-07-27 04:22:15 +00009324 // Build an exception specification pointing back at this member.
9325 FunctionProtoType::ExtProtoInfo EPI;
9326 EPI.ExceptionSpecType = EST_Unevaluated;
9327 EPI.ExceptionSpecDecl = MoveConstructor;
9328 MoveConstructor->setType(
9329 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9330
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009331 // Add the parameter to the constructor.
9332 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9333 ClassLoc, ClassLoc,
9334 /*IdentifierInfo=*/0,
9335 ArgType, /*TInfo=*/0,
9336 SC_None,
9337 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009338 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009339
Richard Smithbc2a35d2012-12-08 08:32:28 +00009340 MoveConstructor->setTrivial(
9341 ClassDecl->needsOverloadResolutionForMoveConstructor()
9342 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9343 : ClassDecl->hasTrivialMoveConstructor());
9344
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009345 // C++0x [class.copy]p9:
9346 // If the definition of a class X does not explicitly declare a move
9347 // constructor, one will be implicitly declared as defaulted if and only if:
9348 // [...]
9349 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009350 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351 // Cache this result so that we don't try to generate this over and over
9352 // on every lookup, leaking memory and wasting time.
9353 ClassDecl->setFailedImplicitMoveConstructor();
9354 return 0;
9355 }
9356
9357 // Note that we have declared this constructor.
9358 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9359
9360 if (Scope *S = getScopeForContext(ClassDecl))
9361 PushOnScopeChains(MoveConstructor, S, false);
9362 ClassDecl->addDecl(MoveConstructor);
9363
9364 return MoveConstructor;
9365}
9366
9367void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9368 CXXConstructorDecl *MoveConstructor) {
9369 assert((MoveConstructor->isDefaulted() &&
9370 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009371 !MoveConstructor->doesThisDeclarationHaveABody() &&
9372 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009373 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9374
9375 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9376 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9377
Eli Friedman9a14db32012-10-18 20:14:08 +00009378 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009379 DiagnosticErrorTrap Trap(Diags);
9380
David Blaikie93c86172013-01-17 05:26:25 +00009381 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382 Trap.hasErrorOccurred()) {
9383 Diag(CurrentLocation, diag::note_member_synthesized_at)
9384 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9385 MoveConstructor->setInvalidDecl();
9386 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009387 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009388 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9389 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009390 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009391 /*isStmtExpr=*/false)
9392 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009393 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009394 }
9395
9396 MoveConstructor->setUsed();
9397
9398 if (ASTMutationListener *L = getASTMutationListener()) {
9399 L->CompletedImplicitDefinition(MoveConstructor);
9400 }
9401}
9402
Douglas Gregore4e68d42012-02-15 19:33:52 +00009403bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9404 return FD->isDeleted() &&
9405 (FD->isDefaulted() || FD->isImplicit()) &&
9406 isa<CXXMethodDecl>(FD);
9407}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009408
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009409/// \brief Mark the call operator of the given lambda closure type as "used".
9410static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9411 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009412 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009413 Lambda->lookup(
9414 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009415 CallOperator->setReferenced();
9416 CallOperator->setUsed();
9417}
9418
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009419void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9420 SourceLocation CurrentLocation,
9421 CXXConversionDecl *Conv)
9422{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009423 CXXRecordDecl *Lambda = Conv->getParent();
9424
9425 // Make sure that the lambda call operator is marked used.
9426 markLambdaCallOperatorUsed(*this, Lambda);
9427
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009428 Conv->setUsed();
9429
Eli Friedman9a14db32012-10-18 20:14:08 +00009430 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009431 DiagnosticErrorTrap Trap(Diags);
9432
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009433 // Return the address of the __invoke function.
9434 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9435 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009436 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009437 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9438 VK_LValue, Conv->getLocation()).take();
9439 assert(FunctionRef && "Can't refer to __invoke function?");
9440 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009441 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009442 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009443 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009444
9445 // Fill in the __invoke function with a dummy implementation. IR generation
9446 // will fill in the actual details.
9447 Invoke->setUsed();
9448 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009449 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009450
9451 if (ASTMutationListener *L = getASTMutationListener()) {
9452 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009453 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009454 }
9455}
9456
9457void Sema::DefineImplicitLambdaToBlockPointerConversion(
9458 SourceLocation CurrentLocation,
9459 CXXConversionDecl *Conv)
9460{
9461 Conv->setUsed();
9462
Eli Friedman9a14db32012-10-18 20:14:08 +00009463 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009464 DiagnosticErrorTrap Trap(Diags);
9465
Douglas Gregorac1303e2012-02-22 05:02:47 +00009466 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009467 Expr *This = ActOnCXXThis(CurrentLocation).take();
9468 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009469
Eli Friedman23f02672012-03-01 04:01:32 +00009470 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9471 Conv->getLocation(),
9472 Conv, DerefThis);
9473
9474 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9475 // behavior. Note that only the general conversion function does this
9476 // (since it's unusable otherwise); in the case where we inline the
9477 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009478 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009479 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9480 CK_CopyAndAutoreleaseBlockObject,
9481 BuildBlock.get(), 0, VK_RValue);
9482
9483 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009484 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009485 Conv->setInvalidDecl();
9486 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009487 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009488
Douglas Gregorac1303e2012-02-22 05:02:47 +00009489 // Create the return statement that returns the block from the conversion
9490 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009491 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009492 if (Return.isInvalid()) {
9493 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9494 Conv->setInvalidDecl();
9495 return;
9496 }
9497
9498 // Set the body of the conversion function.
9499 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009500 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009501 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009502 Conv->getLocation()));
9503
Douglas Gregorac1303e2012-02-22 05:02:47 +00009504 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009505 if (ASTMutationListener *L = getASTMutationListener()) {
9506 L->CompletedImplicitDefinition(Conv);
9507 }
9508}
9509
Douglas Gregorf52757d2012-03-10 06:53:13 +00009510/// \brief Determine whether the given list arguments contains exactly one
9511/// "real" (non-default) argument.
9512static bool hasOneRealArgument(MultiExprArg Args) {
9513 switch (Args.size()) {
9514 case 0:
9515 return false;
9516
9517 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009518 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009519 return false;
9520
9521 // fall through
9522 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009523 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009524 }
9525
9526 return false;
9527}
9528
John McCall60d7b3a2010-08-24 06:29:42 +00009529ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009530Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009531 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009532 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009533 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009534 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009535 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009536 unsigned ConstructKind,
9537 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009538 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009539
Douglas Gregor2f599792010-04-02 18:24:57 +00009540 // C++0x [class.copy]p34:
9541 // When certain criteria are met, an implementation is allowed to
9542 // omit the copy/move construction of a class object, even if the
9543 // copy/move constructor and/or destructor for the object have
9544 // side effects. [...]
9545 // - when a temporary class object that has not been bound to a
9546 // reference (12.2) would be copied/moved to a class object
9547 // with the same cv-unqualified type, the copy/move operation
9548 // can be omitted by constructing the temporary object
9549 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009550 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009551 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009552 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009553 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009554 }
Mike Stump1eb44332009-09-09 15:08:12 +00009555
9556 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009557 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009558 IsListInitialization, RequiresZeroInit,
9559 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009560}
9561
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009562/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9563/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009564ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009565Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9566 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009567 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009568 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009569 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009570 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009571 unsigned ConstructKind,
9572 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009573 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009574 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009575 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009576 HadMultipleCandidates,
9577 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009578 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9579 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009580}
9581
John McCall68c6c9a2010-02-02 09:10:11 +00009582void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009583 if (VD->isInvalidDecl()) return;
9584
John McCall68c6c9a2010-02-02 09:10:11 +00009585 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009586 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009587 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009588 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009589
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009590 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009591 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009592 CheckDestructorAccess(VD->getLocation(), Destructor,
9593 PDiag(diag::err_access_dtor_var)
9594 << VD->getDeclName()
9595 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009596 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009597
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009598 if (!VD->hasGlobalStorage()) return;
9599
9600 // Emit warning for non-trivial dtor in global scope (a real global,
9601 // class-static, function-static).
9602 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9603
9604 // TODO: this should be re-enabled for static locals by !CXAAtExit
9605 if (!VD->isStaticLocal())
9606 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009607}
9608
Douglas Gregor39da0b82009-09-09 23:08:42 +00009609/// \brief Given a constructor and the set of arguments provided for the
9610/// constructor, convert the arguments and add any required default arguments
9611/// to form a proper call to this constructor.
9612///
9613/// \returns true if an error occurred, false otherwise.
9614bool
9615Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9616 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009617 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009618 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009619 bool AllowExplicit,
9620 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009621 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9622 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009623 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009624
9625 const FunctionProtoType *Proto
9626 = Constructor->getType()->getAs<FunctionProtoType>();
9627 assert(Proto && "Constructor without a prototype?");
9628 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009629
9630 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009631 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009632 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009633 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009634 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009635
9636 VariadicCallType CallType =
9637 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009638 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009639 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9640 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009641 CallType, AllowExplicit,
9642 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009643 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009644
9645 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9646
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009647 CheckConstructorCall(Constructor,
9648 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9649 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009650 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009651
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009652 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009653}
9654
Anders Carlsson20d45d22009-12-12 00:32:00 +00009655static inline bool
9656CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9657 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009658 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009659 if (isa<NamespaceDecl>(DC)) {
9660 return SemaRef.Diag(FnDecl->getLocation(),
9661 diag::err_operator_new_delete_declared_in_namespace)
9662 << FnDecl->getDeclName();
9663 }
9664
9665 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009666 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009667 return SemaRef.Diag(FnDecl->getLocation(),
9668 diag::err_operator_new_delete_declared_static)
9669 << FnDecl->getDeclName();
9670 }
9671
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009672 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009673}
9674
Anders Carlsson156c78e2009-12-13 17:53:43 +00009675static inline bool
9676CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9677 CanQualType ExpectedResultType,
9678 CanQualType ExpectedFirstParamType,
9679 unsigned DependentParamTypeDiag,
9680 unsigned InvalidParamTypeDiag) {
9681 QualType ResultType =
9682 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9683
9684 // Check that the result type is not dependent.
9685 if (ResultType->isDependentType())
9686 return SemaRef.Diag(FnDecl->getLocation(),
9687 diag::err_operator_new_delete_dependent_result_type)
9688 << FnDecl->getDeclName() << ExpectedResultType;
9689
9690 // Check that the result type is what we expect.
9691 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9692 return SemaRef.Diag(FnDecl->getLocation(),
9693 diag::err_operator_new_delete_invalid_result_type)
9694 << FnDecl->getDeclName() << ExpectedResultType;
9695
9696 // A function template must have at least 2 parameters.
9697 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9698 return SemaRef.Diag(FnDecl->getLocation(),
9699 diag::err_operator_new_delete_template_too_few_parameters)
9700 << FnDecl->getDeclName();
9701
9702 // The function decl must have at least 1 parameter.
9703 if (FnDecl->getNumParams() == 0)
9704 return SemaRef.Diag(FnDecl->getLocation(),
9705 diag::err_operator_new_delete_too_few_parameters)
9706 << FnDecl->getDeclName();
9707
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009708 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009709 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9710 if (FirstParamType->isDependentType())
9711 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9712 << FnDecl->getDeclName() << ExpectedFirstParamType;
9713
9714 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009715 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009716 ExpectedFirstParamType)
9717 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9718 << FnDecl->getDeclName() << ExpectedFirstParamType;
9719
9720 return false;
9721}
9722
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009723static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009724CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009725 // C++ [basic.stc.dynamic.allocation]p1:
9726 // A program is ill-formed if an allocation function is declared in a
9727 // namespace scope other than global scope or declared static in global
9728 // scope.
9729 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9730 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009731
9732 CanQualType SizeTy =
9733 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9734
9735 // C++ [basic.stc.dynamic.allocation]p1:
9736 // The return type shall be void*. The first parameter shall have type
9737 // std::size_t.
9738 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9739 SizeTy,
9740 diag::err_operator_new_dependent_param_type,
9741 diag::err_operator_new_param_type))
9742 return true;
9743
9744 // C++ [basic.stc.dynamic.allocation]p1:
9745 // The first parameter shall not have an associated default argument.
9746 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009747 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009748 diag::err_operator_new_default_arg)
9749 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9750
9751 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009752}
9753
9754static bool
Richard Smith444d3842012-10-20 08:26:51 +00009755CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009756 // C++ [basic.stc.dynamic.deallocation]p1:
9757 // A program is ill-formed if deallocation functions are declared in a
9758 // namespace scope other than global scope or declared static in global
9759 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009760 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9761 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009762
9763 // C++ [basic.stc.dynamic.deallocation]p2:
9764 // Each deallocation function shall return void and its first parameter
9765 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009766 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9767 SemaRef.Context.VoidPtrTy,
9768 diag::err_operator_delete_dependent_param_type,
9769 diag::err_operator_delete_param_type))
9770 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009771
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009772 return false;
9773}
9774
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009775/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9776/// of this overloaded operator is well-formed. If so, returns false;
9777/// otherwise, emits appropriate diagnostics and returns true.
9778bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009779 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009780 "Expected an overloaded operator declaration");
9781
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009782 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9783
Mike Stump1eb44332009-09-09 15:08:12 +00009784 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009785 // The allocation and deallocation functions, operator new,
9786 // operator new[], operator delete and operator delete[], are
9787 // described completely in 3.7.3. The attributes and restrictions
9788 // found in the rest of this subclause do not apply to them unless
9789 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009790 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009791 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009792
Anders Carlssona3ccda52009-12-12 00:26:23 +00009793 if (Op == OO_New || Op == OO_Array_New)
9794 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009795
9796 // C++ [over.oper]p6:
9797 // An operator function shall either be a non-static member
9798 // function or be a non-member function and have at least one
9799 // parameter whose type is a class, a reference to a class, an
9800 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009801 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9802 if (MethodDecl->isStatic())
9803 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009804 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009805 } else {
9806 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009807 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9808 ParamEnd = FnDecl->param_end();
9809 Param != ParamEnd; ++Param) {
9810 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009811 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9812 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009813 ClassOrEnumParam = true;
9814 break;
9815 }
9816 }
9817
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009818 if (!ClassOrEnumParam)
9819 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009820 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009821 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009822 }
9823
9824 // C++ [over.oper]p8:
9825 // An operator function cannot have default arguments (8.3.6),
9826 // except where explicitly stated below.
9827 //
Mike Stump1eb44332009-09-09 15:08:12 +00009828 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009829 // (C++ [over.call]p1).
9830 if (Op != OO_Call) {
9831 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9832 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009833 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009834 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009835 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009836 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009837 }
9838 }
9839
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009840 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9841 { false, false, false }
9842#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9843 , { Unary, Binary, MemberOnly }
9844#include "clang/Basic/OperatorKinds.def"
9845 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009846
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009847 bool CanBeUnaryOperator = OperatorUses[Op][0];
9848 bool CanBeBinaryOperator = OperatorUses[Op][1];
9849 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009850
9851 // C++ [over.oper]p8:
9852 // [...] Operator functions cannot have more or fewer parameters
9853 // than the number required for the corresponding operator, as
9854 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009855 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009856 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009857 if (Op != OO_Call &&
9858 ((NumParams == 1 && !CanBeUnaryOperator) ||
9859 (NumParams == 2 && !CanBeBinaryOperator) ||
9860 (NumParams < 1) || (NumParams > 2))) {
9861 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009862 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009863 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009864 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009865 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009866 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009867 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009868 assert(CanBeBinaryOperator &&
9869 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009870 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009871 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009872
Chris Lattner416e46f2008-11-21 07:57:12 +00009873 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009874 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009875 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009876
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009877 // Overloaded operators other than operator() cannot be variadic.
9878 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009879 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009880 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009881 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009882 }
9883
9884 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009885 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9886 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009887 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009888 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009889 }
9890
9891 // C++ [over.inc]p1:
9892 // The user-defined function called operator++ implements the
9893 // prefix and postfix ++ operator. If this function is a member
9894 // function with no parameters, or a non-member function with one
9895 // parameter of class or enumeration type, it defines the prefix
9896 // increment operator ++ for objects of that type. If the function
9897 // is a member function with one parameter (which shall be of type
9898 // int) or a non-member function with two parameters (the second
9899 // of which shall be of type int), it defines the postfix
9900 // increment operator ++ for objects of that type.
9901 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9902 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9903 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009904 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009905 ParamIsInt = BT->getKind() == BuiltinType::Int;
9906
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009907 if (!ParamIsInt)
9908 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009909 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009910 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009911 }
9912
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009913 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009914}
Chris Lattner5a003a42008-12-17 07:09:26 +00009915
Sean Hunta6c058d2010-01-13 09:01:02 +00009916/// CheckLiteralOperatorDeclaration - Check whether the declaration
9917/// of this literal operator function is well-formed. If so, returns
9918/// false; otherwise, emits appropriate diagnostics and returns true.
9919bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009920 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009921 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9922 << FnDecl->getDeclName();
9923 return true;
9924 }
9925
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009926 if (FnDecl->isExternC()) {
9927 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9928 return true;
9929 }
9930
Sean Hunta6c058d2010-01-13 09:01:02 +00009931 bool Valid = false;
9932
Richard Smith36f5cfe2012-03-09 08:00:36 +00009933 // This might be the definition of a literal operator template.
9934 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9935 // This might be a specialization of a literal operator template.
9936 if (!TpDecl)
9937 TpDecl = FnDecl->getPrimaryTemplate();
9938
Sean Hunt216c2782010-04-07 23:11:06 +00009939 // template <char...> type operator "" name() is the only valid template
9940 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009941 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009942 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009943 // Must have only one template parameter
9944 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9945 if (Params->size() == 1) {
9946 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009947 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009948
Sean Hunt216c2782010-04-07 23:11:06 +00009949 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009950 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9951 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9952 Valid = true;
9953 }
9954 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009955 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009956 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009957 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9958
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009959 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009960
Sean Hunt30019c02010-04-07 22:57:35 +00009961 // unsigned long long int, long double, and any character type are allowed
9962 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009963 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9964 Context.hasSameType(T, Context.LongDoubleTy) ||
9965 Context.hasSameType(T, Context.CharTy) ||
9966 Context.hasSameType(T, Context.WCharTy) ||
9967 Context.hasSameType(T, Context.Char16Ty) ||
9968 Context.hasSameType(T, Context.Char32Ty)) {
9969 if (++Param == FnDecl->param_end())
9970 Valid = true;
9971 goto FinishedParams;
9972 }
9973
Sean Hunt30019c02010-04-07 22:57:35 +00009974 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009975 const PointerType *PT = T->getAs<PointerType>();
9976 if (!PT)
9977 goto FinishedParams;
9978 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009979 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009980 goto FinishedParams;
9981 T = T.getUnqualifiedType();
9982
9983 // Move on to the second parameter;
9984 ++Param;
9985
9986 // If there is no second parameter, the first must be a const char *
9987 if (Param == FnDecl->param_end()) {
9988 if (Context.hasSameType(T, Context.CharTy))
9989 Valid = true;
9990 goto FinishedParams;
9991 }
9992
9993 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9994 // are allowed as the first parameter to a two-parameter function
9995 if (!(Context.hasSameType(T, Context.CharTy) ||
9996 Context.hasSameType(T, Context.WCharTy) ||
9997 Context.hasSameType(T, Context.Char16Ty) ||
9998 Context.hasSameType(T, Context.Char32Ty)))
9999 goto FinishedParams;
10000
10001 // The second and final parameter must be an std::size_t
10002 T = (*Param)->getType().getUnqualifiedType();
10003 if (Context.hasSameType(T, Context.getSizeType()) &&
10004 ++Param == FnDecl->param_end())
10005 Valid = true;
10006 }
10007
10008 // FIXME: This diagnostic is absolutely terrible.
10009FinishedParams:
10010 if (!Valid) {
10011 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10012 << FnDecl->getDeclName();
10013 return true;
10014 }
10015
Richard Smitha9e88b22012-03-09 08:16:22 +000010016 // A parameter-declaration-clause containing a default argument is not
10017 // equivalent to any of the permitted forms.
10018 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10019 ParamEnd = FnDecl->param_end();
10020 Param != ParamEnd; ++Param) {
10021 if ((*Param)->hasDefaultArg()) {
10022 Diag((*Param)->getDefaultArgRange().getBegin(),
10023 diag::err_literal_operator_default_argument)
10024 << (*Param)->getDefaultArgRange();
10025 break;
10026 }
10027 }
10028
Richard Smith2fb4ae32012-03-08 02:39:21 +000010029 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010030 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10031 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010032 // C++11 [usrlit.suffix]p1:
10033 // Literal suffix identifiers that do not start with an underscore
10034 // are reserved for future standardization.
10035 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010036 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010037
Sean Hunta6c058d2010-01-13 09:01:02 +000010038 return false;
10039}
10040
Douglas Gregor074149e2009-01-05 19:45:36 +000010041/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10042/// linkage specification, including the language and (if present)
10043/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10044/// the location of the language string literal, which is provided
10045/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10046/// the '{' brace. Otherwise, this linkage specification does not
10047/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010048Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10049 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010050 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010051 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010052 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010053 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010054 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010055 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010056 Language = LinkageSpecDecl::lang_cxx;
10057 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010058 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010059 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010060 }
Mike Stump1eb44332009-09-09 15:08:12 +000010061
Chris Lattnercc98eac2008-12-17 07:13:27 +000010062 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010063
Douglas Gregor074149e2009-01-05 19:45:36 +000010064 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010065 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010066 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010067 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010068 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010069}
10070
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010071/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010072/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10073/// valid, it's the position of the closing '}' brace in a linkage
10074/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010075Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010076 Decl *LinkageSpec,
10077 SourceLocation RBraceLoc) {
10078 if (LinkageSpec) {
10079 if (RBraceLoc.isValid()) {
10080 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10081 LSDecl->setRBraceLoc(RBraceLoc);
10082 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010083 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010084 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010085 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010086}
10087
Richard Smith6b3d3e52013-02-20 19:22:51 +000010088/// \brief Perform semantic checks on a C++11 attribute-declaration.
10089void Sema::ActOnAttributeDeclaration(AttributeList *AttrList) {
10090 // FIXME: Build an AST node for an attribute declaration and return it.
10091
10092 // Since we do not support any attributes which can be used in an attribute
10093 // declaration, just diagnose standard and unknown attributes appropriately.
10094 for (/**/; AttrList; AttrList = AttrList->getNext()) {
10095 if (AttrList->getKind() == AttributeList::IgnoredAttribute ||
10096 AttrList->isInvalid())
10097 continue;
10098
10099 Diag(AttrList->getLoc(),
10100 AttrList->getKind() == AttributeList::UnknownAttribute
10101 ? diag::warn_unknown_attribute_ignored
10102 : diag::err_attribute_declaration)
10103 << AttrList->getName();
10104 }
10105}
10106
Douglas Gregord308e622009-05-18 20:51:54 +000010107/// \brief Perform semantic analysis for the variable declaration that
10108/// occurs within a C++ catch clause, returning the newly-created
10109/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010110VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010111 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010112 SourceLocation StartLoc,
10113 SourceLocation Loc,
10114 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010115 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010116 QualType ExDeclType = TInfo->getType();
10117
Sebastian Redl4b07b292008-12-22 19:15:10 +000010118 // Arrays and functions decay.
10119 if (ExDeclType->isArrayType())
10120 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10121 else if (ExDeclType->isFunctionType())
10122 ExDeclType = Context.getPointerType(ExDeclType);
10123
10124 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10125 // The exception-declaration shall not denote a pointer or reference to an
10126 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010127 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010128 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010129 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010130 Invalid = true;
10131 }
Douglas Gregord308e622009-05-18 20:51:54 +000010132
Sebastian Redl4b07b292008-12-22 19:15:10 +000010133 QualType BaseType = ExDeclType;
10134 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010135 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010136 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010137 BaseType = Ptr->getPointeeType();
10138 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010139 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010140 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010141 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010142 BaseType = Ref->getPointeeType();
10143 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010144 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010145 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010146 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010147 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010148 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010149
Mike Stump1eb44332009-09-09 15:08:12 +000010150 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010151 RequireNonAbstractType(Loc, ExDeclType,
10152 diag::err_abstract_type_in_decl,
10153 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010154 Invalid = true;
10155
John McCall5a180392010-07-24 00:37:23 +000010156 // Only the non-fragile NeXT runtime currently supports C++ catches
10157 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010158 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010159 QualType T = ExDeclType;
10160 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10161 T = RT->getPointeeType();
10162
10163 if (T->isObjCObjectType()) {
10164 Diag(Loc, diag::err_objc_object_catch);
10165 Invalid = true;
10166 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010167 // FIXME: should this be a test for macosx-fragile specifically?
10168 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010169 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010170 }
10171 }
10172
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010173 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10174 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010175 ExDecl->setExceptionVariable(true);
10176
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010177 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010178 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010179 Invalid = true;
10180
Douglas Gregorc41b8782011-07-06 18:14:43 +000010181 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010182 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010183 // C++ [except.handle]p16:
10184 // The object declared in an exception-declaration or, if the
10185 // exception-declaration does not specify a name, a temporary (12.2) is
10186 // copy-initialized (8.5) from the exception object. [...]
10187 // The object is destroyed when the handler exits, after the destruction
10188 // of any automatic objects initialized within the handler.
10189 //
10190 // We just pretend to initialize the object with itself, then make sure
10191 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010192 QualType initType = ExDeclType;
10193
10194 InitializedEntity entity =
10195 InitializedEntity::InitializeVariable(ExDecl);
10196 InitializationKind initKind =
10197 InitializationKind::CreateCopy(Loc, SourceLocation());
10198
10199 Expr *opaqueValue =
10200 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10201 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10202 ExprResult result = sequence.Perform(*this, entity, initKind,
10203 MultiExprArg(&opaqueValue, 1));
10204 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010205 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010206 else {
10207 // If the constructor used was non-trivial, set this as the
10208 // "initializer".
10209 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10210 if (!construct->getConstructor()->isTrivial()) {
10211 Expr *init = MaybeCreateExprWithCleanups(construct);
10212 ExDecl->setInit(init);
10213 }
10214
10215 // And make sure it's destructable.
10216 FinalizeVarWithDestructor(ExDecl, recordType);
10217 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010218 }
10219 }
10220
Douglas Gregord308e622009-05-18 20:51:54 +000010221 if (Invalid)
10222 ExDecl->setInvalidDecl();
10223
10224 return ExDecl;
10225}
10226
10227/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10228/// handler.
John McCalld226f652010-08-21 09:40:31 +000010229Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010230 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010231 bool Invalid = D.isInvalidType();
10232
10233 // Check for unexpanded parameter packs.
10234 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10235 UPPC_ExceptionType)) {
10236 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10237 D.getIdentifierLoc());
10238 Invalid = true;
10239 }
10240
Sebastian Redl4b07b292008-12-22 19:15:10 +000010241 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010242 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010243 LookupOrdinaryName,
10244 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010245 // The scope should be freshly made just for us. There is just no way
10246 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010247 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010248 if (PrevDecl->isTemplateParameter()) {
10249 // Maybe we will complain about the shadowed template parameter.
10250 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010251 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010252 }
10253 }
10254
Chris Lattnereaaebc72009-04-25 08:06:05 +000010255 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010256 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10257 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010258 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010259 }
10260
Douglas Gregor83cb9422010-09-09 17:09:21 +000010261 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010262 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010263 D.getIdentifierLoc(),
10264 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010265 if (Invalid)
10266 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010267
Sebastian Redl4b07b292008-12-22 19:15:10 +000010268 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010269 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010270 PushOnScopeChains(ExDecl, S);
10271 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010272 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010273
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010274 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010275 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010276}
Anders Carlssonfb311762009-03-14 00:25:26 +000010277
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010278Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010279 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010280 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010281 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010282 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010283
Richard Smithe3f470a2012-07-11 22:37:56 +000010284 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10285 return 0;
10286
10287 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10288 AssertMessage, RParenLoc, false);
10289}
10290
10291Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10292 Expr *AssertExpr,
10293 StringLiteral *AssertMessage,
10294 SourceLocation RParenLoc,
10295 bool Failed) {
10296 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10297 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010298 // In a static_assert-declaration, the constant-expression shall be a
10299 // constant expression that can be contextually converted to bool.
10300 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10301 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010302 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010303
Richard Smithdaaefc52011-12-14 23:32:26 +000010304 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010305 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010306 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010307 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010308 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010309
Richard Smithe3f470a2012-07-11 22:37:56 +000010310 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010311 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010312 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010313 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010314 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010315 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010316 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010317 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010318 }
Mike Stump1eb44332009-09-09 15:08:12 +000010319
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010320 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010321 AssertExpr, AssertMessage, RParenLoc,
10322 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010323
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010324 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010325 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010326}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010327
Douglas Gregor1d869352010-04-07 16:53:43 +000010328/// \brief Perform semantic analysis of the given friend type declaration.
10329///
10330/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010331FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010332 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010333 TypeSourceInfo *TSInfo) {
10334 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10335
10336 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010337 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010338
Richard Smith6b130222011-10-18 21:39:00 +000010339 // C++03 [class.friend]p2:
10340 // An elaborated-type-specifier shall be used in a friend declaration
10341 // for a class.*
10342 //
10343 // * The class-key of the elaborated-type-specifier is required.
10344 if (!ActiveTemplateInstantiations.empty()) {
10345 // Do not complain about the form of friend template types during
10346 // template instantiation; we will already have complained when the
10347 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010348 } else {
10349 if (!T->isElaboratedTypeSpecifier()) {
10350 // If we evaluated the type to a record type, suggest putting
10351 // a tag in front.
10352 if (const RecordType *RT = T->getAs<RecordType>()) {
10353 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010354
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010355 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010356
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010357 Diag(TypeRange.getBegin(),
10358 getLangOpts().CPlusPlus11 ?
10359 diag::warn_cxx98_compat_unelaborated_friend_type :
10360 diag::ext_unelaborated_friend_type)
10361 << (unsigned) RD->getTagKind()
10362 << T
10363 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10364 InsertionText);
10365 } else {
10366 Diag(FriendLoc,
10367 getLangOpts().CPlusPlus11 ?
10368 diag::warn_cxx98_compat_nonclass_type_friend :
10369 diag::ext_nonclass_type_friend)
10370 << T
10371 << TypeRange;
10372 }
10373 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010374 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010375 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010376 diag::warn_cxx98_compat_enum_friend :
10377 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010378 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010379 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010380 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010381
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010382 // C++11 [class.friend]p3:
10383 // A friend declaration that does not declare a function shall have one
10384 // of the following forms:
10385 // friend elaborated-type-specifier ;
10386 // friend simple-type-specifier ;
10387 // friend typename-specifier ;
10388 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10389 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10390 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010391
Douglas Gregor06245bf2010-04-07 17:57:12 +000010392 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010393 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010394 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010395 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010396}
10397
John McCall9a34edb2010-10-19 01:40:49 +000010398/// Handle a friend tag declaration where the scope specifier was
10399/// templated.
10400Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10401 unsigned TagSpec, SourceLocation TagLoc,
10402 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010403 IdentifierInfo *Name,
10404 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010405 AttributeList *Attr,
10406 MultiTemplateParamsArg TempParamLists) {
10407 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10408
10409 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010410 bool Invalid = false;
10411
10412 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010413 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010414 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010415 TempParamLists.size(),
10416 /*friend*/ true,
10417 isExplicitSpecialization,
10418 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010419 if (TemplateParams->size() > 0) {
10420 // This is a declaration of a class template.
10421 if (Invalid)
10422 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010423
Eric Christopher4110e132011-07-21 05:34:24 +000010424 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10425 SS, Name, NameLoc, Attr,
10426 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010427 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010428 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010429 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010430 } else {
10431 // The "template<>" header is extraneous.
10432 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10433 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10434 isExplicitSpecialization = true;
10435 }
10436 }
10437
10438 if (Invalid) return 0;
10439
John McCall9a34edb2010-10-19 01:40:49 +000010440 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010441 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010442 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010443 isAllExplicitSpecializations = false;
10444 break;
10445 }
10446 }
10447
10448 // FIXME: don't ignore attributes.
10449
10450 // If it's explicit specializations all the way down, just forget
10451 // about the template header and build an appropriate non-templated
10452 // friend. TODO: for source fidelity, remember the headers.
10453 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010454 if (SS.isEmpty()) {
10455 bool Owned = false;
10456 bool IsDependent = false;
10457 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10458 Attr, AS_public,
10459 /*ModulePrivateLoc=*/SourceLocation(),
10460 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010461 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010462 /*ScopedEnumUsesClassTag=*/false,
10463 /*UnderlyingType=*/TypeResult());
10464 }
10465
Douglas Gregor2494dd02011-03-01 01:34:45 +000010466 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010467 ElaboratedTypeKeyword Keyword
10468 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010469 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010470 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010471 if (T.isNull())
10472 return 0;
10473
10474 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10475 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010476 DependentNameTypeLoc TL =
10477 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010478 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010479 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010480 TL.setNameLoc(NameLoc);
10481 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010482 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010483 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010484 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010485 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010486 }
10487
10488 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010489 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010490 Friend->setAccess(AS_public);
10491 CurContext->addDecl(Friend);
10492 return Friend;
10493 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010494
10495 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10496
10497
John McCall9a34edb2010-10-19 01:40:49 +000010498
10499 // Handle the case of a templated-scope friend class. e.g.
10500 // template <class T> class A<T>::B;
10501 // FIXME: we don't support these right now.
10502 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10503 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10504 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010505 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010506 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010507 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010508 TL.setNameLoc(NameLoc);
10509
10510 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010511 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010512 Friend->setAccess(AS_public);
10513 Friend->setUnsupportedFriend(true);
10514 CurContext->addDecl(Friend);
10515 return Friend;
10516}
10517
10518
John McCalldd4a3b02009-09-16 22:47:08 +000010519/// Handle a friend type declaration. This works in tandem with
10520/// ActOnTag.
10521///
10522/// Notes on friend class templates:
10523///
10524/// We generally treat friend class declarations as if they were
10525/// declaring a class. So, for example, the elaborated type specifier
10526/// in a friend declaration is required to obey the restrictions of a
10527/// class-head (i.e. no typedefs in the scope chain), template
10528/// parameters are required to match up with simple template-ids, &c.
10529/// However, unlike when declaring a template specialization, it's
10530/// okay to refer to a template specialization without an empty
10531/// template parameter declaration, e.g.
10532/// friend class A<T>::B<unsigned>;
10533/// We permit this as a special case; if there are any template
10534/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010535/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010536Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010537 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010538 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010539
10540 assert(DS.isFriendSpecified());
10541 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10542
John McCalldd4a3b02009-09-16 22:47:08 +000010543 // Try to convert the decl specifier to a type. This works for
10544 // friend templates because ActOnTag never produces a ClassTemplateDecl
10545 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010546 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010547 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10548 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010549 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010550 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010551
Douglas Gregor6ccab972010-12-16 01:14:37 +000010552 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10553 return 0;
10554
John McCalldd4a3b02009-09-16 22:47:08 +000010555 // This is definitely an error in C++98. It's probably meant to
10556 // be forbidden in C++0x, too, but the specification is just
10557 // poorly written.
10558 //
10559 // The problem is with declarations like the following:
10560 // template <T> friend A<T>::foo;
10561 // where deciding whether a class C is a friend or not now hinges
10562 // on whether there exists an instantiation of A that causes
10563 // 'foo' to equal C. There are restrictions on class-heads
10564 // (which we declare (by fiat) elaborated friend declarations to
10565 // be) that makes this tractable.
10566 //
10567 // FIXME: handle "template <> friend class A<T>;", which
10568 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010569 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010570 Diag(Loc, diag::err_tagless_friend_type_template)
10571 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010572 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010573 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010574
John McCall02cace72009-08-28 07:59:38 +000010575 // C++98 [class.friend]p1: A friend of a class is a function
10576 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010577 // This is fixed in DR77, which just barely didn't make the C++03
10578 // deadline. It's also a very silly restriction that seriously
10579 // affects inner classes and which nobody else seems to implement;
10580 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010581 //
10582 // But note that we could warn about it: it's always useless to
10583 // friend one of your own members (it's not, however, worthless to
10584 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010585
John McCalldd4a3b02009-09-16 22:47:08 +000010586 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010587 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010588 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010589 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010590 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010591 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010592 DS.getFriendSpecLoc());
10593 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010594 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010595
10596 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010597 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010598
John McCalldd4a3b02009-09-16 22:47:08 +000010599 D->setAccess(AS_public);
10600 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010601
John McCalld226f652010-08-21 09:40:31 +000010602 return D;
John McCall02cace72009-08-28 07:59:38 +000010603}
10604
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010605NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10606 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010607 const DeclSpec &DS = D.getDeclSpec();
10608
10609 assert(DS.isFriendSpecified());
10610 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10611
10612 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010613 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010614
10615 // C++ [class.friend]p1
10616 // A friend of a class is a function or class....
10617 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010618 // It *doesn't* see through dependent types, which is correct
10619 // according to [temp.arg.type]p3:
10620 // If a declaration acquires a function type through a
10621 // type dependent on a template-parameter and this causes
10622 // a declaration that does not use the syntactic form of a
10623 // function declarator to have a function type, the program
10624 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010625 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010626 Diag(Loc, diag::err_unexpected_friend);
10627
10628 // It might be worthwhile to try to recover by creating an
10629 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010630 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010631 }
10632
10633 // C++ [namespace.memdef]p3
10634 // - If a friend declaration in a non-local class first declares a
10635 // class or function, the friend class or function is a member
10636 // of the innermost enclosing namespace.
10637 // - The name of the friend is not found by simple name lookup
10638 // until a matching declaration is provided in that namespace
10639 // scope (either before or after the class declaration granting
10640 // friendship).
10641 // - If a friend function is called, its name may be found by the
10642 // name lookup that considers functions from namespaces and
10643 // classes associated with the types of the function arguments.
10644 // - When looking for a prior declaration of a class or a function
10645 // declared as a friend, scopes outside the innermost enclosing
10646 // namespace scope are not considered.
10647
John McCall337ec3d2010-10-12 23:13:28 +000010648 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010649 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10650 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010651 assert(Name);
10652
Douglas Gregor6ccab972010-12-16 01:14:37 +000010653 // Check for unexpanded parameter packs.
10654 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10655 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10656 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10657 return 0;
10658
John McCall67d1a672009-08-06 02:15:43 +000010659 // The context we found the declaration in, or in which we should
10660 // create the declaration.
10661 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010662 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010663 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010664 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010665
John McCall337ec3d2010-10-12 23:13:28 +000010666 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010667
John McCall337ec3d2010-10-12 23:13:28 +000010668 // There are four cases here.
10669 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010670 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010671 // there as appropriate.
10672 // Recover from invalid scope qualifiers as if they just weren't there.
10673 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010674 // C++0x [namespace.memdef]p3:
10675 // If the name in a friend declaration is neither qualified nor
10676 // a template-id and the declaration is a function or an
10677 // elaborated-type-specifier, the lookup to determine whether
10678 // the entity has been previously declared shall not consider
10679 // any scopes outside the innermost enclosing namespace.
10680 // C++0x [class.friend]p11:
10681 // If a friend declaration appears in a local class and the name
10682 // specified is an unqualified name, a prior declaration is
10683 // looked up without considering scopes that are outside the
10684 // innermost enclosing non-class scope. For a friend function
10685 // declaration, if there is no prior declaration, the program is
10686 // ill-formed.
10687 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010688 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010689
John McCall29ae6e52010-10-13 05:45:15 +000010690 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010691 DC = CurContext;
10692 while (true) {
10693 // Skip class contexts. If someone can cite chapter and verse
10694 // for this behavior, that would be nice --- it's what GCC and
10695 // EDG do, and it seems like a reasonable intent, but the spec
10696 // really only says that checks for unqualified existing
10697 // declarations should stop at the nearest enclosing namespace,
10698 // not that they should only consider the nearest enclosing
10699 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010700 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010701 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010702
John McCall68263142009-11-18 22:49:29 +000010703 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010704
10705 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010706 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010707 break;
John McCall29ae6e52010-10-13 05:45:15 +000010708
John McCall8a407372010-10-14 22:22:28 +000010709 if (isTemplateId) {
10710 if (isa<TranslationUnitDecl>(DC)) break;
10711 } else {
10712 if (DC->isFileContext()) break;
10713 }
John McCall67d1a672009-08-06 02:15:43 +000010714 DC = DC->getParent();
10715 }
10716
10717 // C++ [class.friend]p1: A friend of a class is a function or
10718 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010719 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010720 // Most C++ 98 compilers do seem to give an error here, so
10721 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010722 if (!Previous.empty() && DC->Equals(CurContext))
10723 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010724 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010725 diag::warn_cxx98_compat_friend_is_member :
10726 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010727
John McCall380aaa42010-10-13 06:22:15 +000010728 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010729
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.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010734 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010735 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10736 }
10737
John McCall337ec3d2010-10-12 23:13:28 +000010738 // - There's a non-dependent scope specifier, in which case we
10739 // compute it and do a previous lookup there for a function
10740 // or function template.
10741 } else if (!SS.getScopeRep()->isDependent()) {
10742 DC = computeDeclContext(SS);
10743 if (!DC) return 0;
10744
10745 if (RequireCompleteDeclContext(SS, DC)) return 0;
10746
10747 LookupQualifiedName(Previous, DC);
10748
10749 // Ignore things found implicitly in the wrong scope.
10750 // TODO: better diagnostics for this case. Suggesting the right
10751 // qualified scope would be nice...
10752 LookupResult::Filter F = Previous.makeFilter();
10753 while (F.hasNext()) {
10754 NamedDecl *D = F.next();
10755 if (!DC->InEnclosingNamespaceSetOf(
10756 D->getDeclContext()->getRedeclContext()))
10757 F.erase();
10758 }
10759 F.done();
10760
10761 if (Previous.empty()) {
10762 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010763 Diag(Loc, diag::err_qualified_friend_not_found)
10764 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010765 return 0;
10766 }
10767
10768 // C++ [class.friend]p1: A friend of a class is a function or
10769 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010770 if (DC->Equals(CurContext))
10771 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010772 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010773 diag::warn_cxx98_compat_friend_is_member :
10774 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010775
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010776 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010777 // C++ [class.friend]p6:
10778 // A function can be defined in a friend declaration of a class if and
10779 // only if the class is a non-local class (9.8), the function name is
10780 // unqualified, and the function has namespace scope.
10781 SemaDiagnosticBuilder DB
10782 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10783
10784 DB << SS.getScopeRep();
10785 if (DC->isFileContext())
10786 DB << FixItHint::CreateRemoval(SS.getRange());
10787 SS.clear();
10788 }
John McCall337ec3d2010-10-12 23:13:28 +000010789
10790 // - There's a scope specifier that does not match any template
10791 // parameter lists, in which case we use some arbitrary context,
10792 // create a method or method template, and wait for instantiation.
10793 // - There's a scope specifier that does match some template
10794 // parameter lists, which we don't handle right now.
10795 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010796 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010797 // C++ [class.friend]p6:
10798 // A function can be defined in a friend declaration of a class if and
10799 // only if the class is a non-local class (9.8), the function name is
10800 // unqualified, and the function has namespace scope.
10801 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10802 << SS.getScopeRep();
10803 }
10804
John McCall337ec3d2010-10-12 23:13:28 +000010805 DC = CurContext;
10806 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010807 }
Douglas Gregor883af832011-10-10 01:11:59 +000010808
John McCall29ae6e52010-10-13 05:45:15 +000010809 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010810 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010811 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10812 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10813 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010814 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010815 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10816 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010817 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010818 }
John McCall67d1a672009-08-06 02:15:43 +000010819 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010820
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010821 // FIXME: This is an egregious hack to cope with cases where the scope stack
10822 // does not contain the declaration context, i.e., in an out-of-line
10823 // definition of a class.
10824 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10825 if (!DCScope) {
10826 FakeDCScope.setEntity(DC);
10827 DCScope = &FakeDCScope;
10828 }
10829
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010830 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010831 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010832 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010833 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010834
Douglas Gregor182ddf02009-09-28 00:08:27 +000010835 assert(ND->getDeclContext() == DC);
10836 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010837
John McCallab88d972009-08-31 22:39:49 +000010838 // Add the function declaration to the appropriate lookup tables,
10839 // adjusting the redeclarations list as necessary. We don't
10840 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010841 //
John McCallab88d972009-08-31 22:39:49 +000010842 // Also update the scope-based lookup if the target context's
10843 // lookup context is in lexical scope.
10844 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010845 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010846 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010847 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010848 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010849 }
John McCall02cace72009-08-28 07:59:38 +000010850
10851 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010852 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010853 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010854 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010855 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010856
John McCall1f2e1a92012-08-10 03:15:35 +000010857 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010858 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010859 } else {
10860 if (DC->isRecord()) CheckFriendAccess(ND);
10861
John McCall6102ca12010-10-16 06:59:13 +000010862 FunctionDecl *FD;
10863 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10864 FD = FTD->getTemplatedDecl();
10865 else
10866 FD = cast<FunctionDecl>(ND);
10867
10868 // Mark templated-scope function declarations as unsupported.
10869 if (FD->getNumTemplateParameterLists())
10870 FrD->setUnsupportedFriend(true);
10871 }
John McCall337ec3d2010-10-12 23:13:28 +000010872
John McCalld226f652010-08-21 09:40:31 +000010873 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010874}
10875
John McCalld226f652010-08-21 09:40:31 +000010876void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10877 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010878
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010879 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010880 if (!Fn) {
10881 Diag(DelLoc, diag::err_deleted_non_function);
10882 return;
10883 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010884 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010885 // Don't consider the implicit declaration we generate for explicit
10886 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010887 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10888 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010889 Diag(DelLoc, diag::err_deleted_decl_not_first);
10890 Diag(Prev->getLocation(), diag::note_previous_declaration);
10891 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010892 // If the declaration wasn't the first, we delete the function anyway for
10893 // recovery.
10894 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010895 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010896}
Sebastian Redl13e88542009-04-27 21:33:24 +000010897
Sean Hunte4246a62011-05-12 06:15:49 +000010898void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010899 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000010900
10901 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010902 if (MD->getParent()->isDependentType()) {
10903 MD->setDefaulted();
10904 MD->setExplicitlyDefaulted();
10905 return;
10906 }
10907
Sean Hunte4246a62011-05-12 06:15:49 +000010908 CXXSpecialMember Member = getSpecialMember(MD);
10909 if (Member == CXXInvalid) {
10910 Diag(DefaultLoc, diag::err_default_special_members);
10911 return;
10912 }
10913
10914 MD->setDefaulted();
10915 MD->setExplicitlyDefaulted();
10916
Sean Huntcd10dec2011-05-23 23:14:04 +000010917 // If this definition appears within the record, do the checking when
10918 // the record is complete.
10919 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010920 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010921 // Find the uninstantiated declaration that actually had the '= default'
10922 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010923 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010924
10925 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010926 return;
10927
Richard Smithb9d0b762012-07-27 04:22:15 +000010928 CheckExplicitlyDefaultedSpecialMember(MD);
10929
Richard Smith1d28caf2012-12-11 01:14:52 +000010930 // The exception specification is needed because we are defining the
10931 // function.
10932 ResolveExceptionSpec(DefaultLoc,
10933 MD->getType()->castAs<FunctionProtoType>());
10934
Sean Hunte4246a62011-05-12 06:15:49 +000010935 switch (Member) {
10936 case CXXDefaultConstructor: {
10937 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010938 if (!CD->isInvalidDecl())
10939 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10940 break;
10941 }
10942
10943 case CXXCopyConstructor: {
10944 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010945 if (!CD->isInvalidDecl())
10946 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010947 break;
10948 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010949
Sean Hunt2b188082011-05-14 05:23:28 +000010950 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010951 if (!MD->isInvalidDecl())
10952 DefineImplicitCopyAssignment(DefaultLoc, MD);
10953 break;
10954 }
10955
Sean Huntcb45a0f2011-05-12 22:46:25 +000010956 case CXXDestructor: {
10957 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010958 if (!DD->isInvalidDecl())
10959 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010960 break;
10961 }
10962
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010963 case CXXMoveConstructor: {
10964 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010965 if (!CD->isInvalidDecl())
10966 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010967 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010968 }
Sean Hunt82713172011-05-25 23:16:36 +000010969
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010970 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010971 if (!MD->isInvalidDecl())
10972 DefineImplicitMoveAssignment(DefaultLoc, MD);
10973 break;
10974 }
10975
10976 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010977 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010978 }
10979 } else {
10980 Diag(DefaultLoc, diag::err_default_special_members);
10981 }
10982}
10983
Sebastian Redl13e88542009-04-27 21:33:24 +000010984static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010985 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010986 Stmt *SubStmt = *CI;
10987 if (!SubStmt)
10988 continue;
10989 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010990 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010991 diag::err_return_in_constructor_handler);
10992 if (!isa<Expr>(SubStmt))
10993 SearchForReturnInStmt(Self, SubStmt);
10994 }
10995}
10996
10997void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10998 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10999 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11000 SearchForReturnInStmt(*this, Handler);
11001 }
11002}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011003
David Blaikie299adab2013-01-18 23:03:15 +000011004bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011005 const CXXMethodDecl *Old) {
11006 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11007 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11008
11009 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11010
11011 // If the calling conventions match, everything is fine
11012 if (NewCC == OldCC)
11013 return false;
11014
11015 // If either of the calling conventions are set to "default", we need to pick
11016 // something more sensible based on the target. This supports code where the
11017 // one method explicitly sets thiscall, and another has no explicit calling
11018 // convention.
11019 CallingConv Default =
11020 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11021 if (NewCC == CC_Default)
11022 NewCC = Default;
11023 if (OldCC == CC_Default)
11024 OldCC = Default;
11025
11026 // If the calling conventions still don't match, then report the error
11027 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011028 Diag(New->getLocation(),
11029 diag::err_conflicting_overriding_cc_attributes)
11030 << New->getDeclName() << New->getType() << Old->getType();
11031 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11032 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011033 }
11034
11035 return false;
11036}
11037
Mike Stump1eb44332009-09-09 15:08:12 +000011038bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011039 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011040 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11041 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011042
Chandler Carruth73857792010-02-15 11:53:20 +000011043 if (Context.hasSameType(NewTy, OldTy) ||
11044 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011045 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011046
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011047 // Check if the return types are covariant
11048 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011049
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011050 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011051 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11052 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011053 NewClassTy = NewPT->getPointeeType();
11054 OldClassTy = OldPT->getPointeeType();
11055 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011056 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11057 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11058 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11059 NewClassTy = NewRT->getPointeeType();
11060 OldClassTy = OldRT->getPointeeType();
11061 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011062 }
11063 }
Mike Stump1eb44332009-09-09 15:08:12 +000011064
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011065 // The return types aren't either both pointers or references to a class type.
11066 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011067 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011068 diag::err_different_return_type_for_overriding_virtual_function)
11069 << New->getDeclName() << NewTy << OldTy;
11070 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011071
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011072 return true;
11073 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011074
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011075 // C++ [class.virtual]p6:
11076 // If the return type of D::f differs from the return type of B::f, the
11077 // class type in the return type of D::f shall be complete at the point of
11078 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011079 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11080 if (!RT->isBeingDefined() &&
11081 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011082 diag::err_covariant_return_incomplete,
11083 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011084 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011085 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011086
Douglas Gregora4923eb2009-11-16 21:35:15 +000011087 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011088 // Check if the new class derives from the old class.
11089 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11090 Diag(New->getLocation(),
11091 diag::err_covariant_return_not_derived)
11092 << New->getDeclName() << NewTy << OldTy;
11093 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11094 return true;
11095 }
Mike Stump1eb44332009-09-09 15:08:12 +000011096
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011097 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011098 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011099 diag::err_covariant_return_inaccessible_base,
11100 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11101 // FIXME: Should this point to the return type?
11102 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011103 // FIXME: this note won't trigger for delayed access control
11104 // diagnostics, and it's impossible to get an undelayed error
11105 // here from access control during the original parse because
11106 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011107 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11108 return true;
11109 }
11110 }
Mike Stump1eb44332009-09-09 15:08:12 +000011111
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011112 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011113 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011114 Diag(New->getLocation(),
11115 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011116 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011117 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11118 return true;
11119 };
Mike Stump1eb44332009-09-09 15:08:12 +000011120
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011121
11122 // The new class type must have the same or less qualifiers as the old type.
11123 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11124 Diag(New->getLocation(),
11125 diag::err_covariant_return_type_class_type_more_qualified)
11126 << New->getDeclName() << NewTy << OldTy;
11127 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11128 return true;
11129 };
Mike Stump1eb44332009-09-09 15:08:12 +000011130
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011131 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011132}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011133
Douglas Gregor4ba31362009-12-01 17:24:26 +000011134/// \brief Mark the given method pure.
11135///
11136/// \param Method the method to be marked pure.
11137///
11138/// \param InitRange the source range that covers the "0" initializer.
11139bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011140 SourceLocation EndLoc = InitRange.getEnd();
11141 if (EndLoc.isValid())
11142 Method->setRangeEnd(EndLoc);
11143
Douglas Gregor4ba31362009-12-01 17:24:26 +000011144 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11145 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011146 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011147 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011148
11149 if (!Method->isInvalidDecl())
11150 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11151 << Method->getDeclName() << InitRange;
11152 return true;
11153}
11154
Douglas Gregor552e2992012-02-21 02:22:07 +000011155/// \brief Determine whether the given declaration is a static data member.
11156static bool isStaticDataMember(Decl *D) {
11157 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11158 if (!Var)
11159 return false;
11160
11161 return Var->isStaticDataMember();
11162}
John McCall731ad842009-12-19 09:28:58 +000011163/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11164/// an initializer for the out-of-line declaration 'Dcl'. The scope
11165/// is a fresh scope pushed for just this purpose.
11166///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011167/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11168/// static data member of class X, names should be looked up in the scope of
11169/// class X.
John McCalld226f652010-08-21 09:40:31 +000011170void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011171 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011172 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011173
John McCall731ad842009-12-19 09:28:58 +000011174 // We should only get called for declarations with scope specifiers, like:
11175 // int foo::bar;
11176 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011177 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011178
11179 // If we are parsing the initializer for a static data member, push a
11180 // new expression evaluation context that is associated with this static
11181 // data member.
11182 if (isStaticDataMember(D))
11183 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011184}
11185
11186/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011187/// initializer for the out-of-line declaration 'D'.
11188void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011189 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011190 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011191
Douglas Gregor552e2992012-02-21 02:22:07 +000011192 if (isStaticDataMember(D))
11193 PopExpressionEvaluationContext();
11194
John McCall731ad842009-12-19 09:28:58 +000011195 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011196 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011197}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011198
11199/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11200/// C++ if/switch/while/for statement.
11201/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011202DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011203 // C++ 6.4p2:
11204 // The declarator shall not specify a function or an array.
11205 // The type-specifier-seq shall not contain typedef and shall not declare a
11206 // new class or enumeration.
11207 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11208 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011209
11210 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011211 if (!Dcl)
11212 return true;
11213
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011214 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11215 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011216 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011217 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011218 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011219
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011220 return Dcl;
11221}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011222
Douglas Gregordfe65432011-07-28 19:11:31 +000011223void Sema::LoadExternalVTableUses() {
11224 if (!ExternalSource)
11225 return;
11226
11227 SmallVector<ExternalVTableUse, 4> VTables;
11228 ExternalSource->ReadUsedVTables(VTables);
11229 SmallVector<VTableUse, 4> NewUses;
11230 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11231 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11232 = VTablesUsed.find(VTables[I].Record);
11233 // Even if a definition wasn't required before, it may be required now.
11234 if (Pos != VTablesUsed.end()) {
11235 if (!Pos->second && VTables[I].DefinitionRequired)
11236 Pos->second = true;
11237 continue;
11238 }
11239
11240 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11241 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11242 }
11243
11244 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11245}
11246
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011247void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11248 bool DefinitionRequired) {
11249 // Ignore any vtable uses in unevaluated operands or for classes that do
11250 // not have a vtable.
11251 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11252 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011253 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011254 return;
11255
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011256 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011257 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011258 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11259 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11260 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11261 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011262 // If we already had an entry, check to see if we are promoting this vtable
11263 // to required a definition. If so, we need to reappend to the VTableUses
11264 // list, since we may have already processed the first entry.
11265 if (DefinitionRequired && !Pos.first->second) {
11266 Pos.first->second = true;
11267 } else {
11268 // Otherwise, we can early exit.
11269 return;
11270 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011271 }
11272
11273 // Local classes need to have their virtual members marked
11274 // immediately. For all other classes, we mark their virtual members
11275 // at the end of the translation unit.
11276 if (Class->isLocalClass())
11277 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011278 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011279 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011280}
11281
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011282bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011283 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011284 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011285 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011286
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011287 // Note: The VTableUses vector could grow as a result of marking
11288 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011289 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011290 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011291 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011292 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011293 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011294 if (!Class)
11295 continue;
11296
11297 SourceLocation Loc = VTableUses[I].second;
11298
Richard Smithb9d0b762012-07-27 04:22:15 +000011299 bool DefineVTable = true;
11300
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011301 // If this class has a key function, but that key function is
11302 // defined in another translation unit, we don't need to emit the
11303 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011304 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011305 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011306 switch (KeyFunction->getTemplateSpecializationKind()) {
11307 case TSK_Undeclared:
11308 case TSK_ExplicitSpecialization:
11309 case TSK_ExplicitInstantiationDeclaration:
11310 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011311 DefineVTable = false;
11312 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011313
11314 case TSK_ExplicitInstantiationDefinition:
11315 case TSK_ImplicitInstantiation:
11316 // We will be instantiating the key function.
11317 break;
11318 }
11319 } else if (!KeyFunction) {
11320 // If we have a class with no key function that is the subject
11321 // of an explicit instantiation declaration, suppress the
11322 // vtable; it will live with the explicit instantiation
11323 // definition.
11324 bool IsExplicitInstantiationDeclaration
11325 = Class->getTemplateSpecializationKind()
11326 == TSK_ExplicitInstantiationDeclaration;
11327 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11328 REnd = Class->redecls_end();
11329 R != REnd; ++R) {
11330 TemplateSpecializationKind TSK
11331 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11332 if (TSK == TSK_ExplicitInstantiationDeclaration)
11333 IsExplicitInstantiationDeclaration = true;
11334 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11335 IsExplicitInstantiationDeclaration = false;
11336 break;
11337 }
11338 }
11339
11340 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011341 DefineVTable = false;
11342 }
11343
11344 // The exception specifications for all virtual members may be needed even
11345 // if we are not providing an authoritative form of the vtable in this TU.
11346 // We may choose to emit it available_externally anyway.
11347 if (!DefineVTable) {
11348 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11349 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011350 }
11351
11352 // Mark all of the virtual members of this class as referenced, so
11353 // that we can build a vtable. Then, tell the AST consumer that a
11354 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011355 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011356 MarkVirtualMembersReferenced(Loc, Class);
11357 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11358 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11359
11360 // Optionally warn if we're emitting a weak vtable.
11361 if (Class->getLinkage() == ExternalLinkage &&
11362 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011363 const FunctionDecl *KeyFunctionDef = 0;
11364 if (!KeyFunction ||
11365 (KeyFunction->hasBody(KeyFunctionDef) &&
11366 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011367 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11368 TSK_ExplicitInstantiationDefinition
11369 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11370 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011371 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011372 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011373 VTableUses.clear();
11374
Douglas Gregor78844032011-04-22 22:25:37 +000011375 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011376}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011377
Richard Smithb9d0b762012-07-27 04:22:15 +000011378void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11379 const CXXRecordDecl *RD) {
11380 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11381 E = RD->method_end(); I != E; ++I)
11382 if ((*I)->isVirtual() && !(*I)->isPure())
11383 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11384}
11385
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011386void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11387 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011388 // Mark all functions which will appear in RD's vtable as used.
11389 CXXFinalOverriderMap FinalOverriders;
11390 RD->getFinalOverriders(FinalOverriders);
11391 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11392 E = FinalOverriders.end();
11393 I != E; ++I) {
11394 for (OverridingMethods::const_iterator OI = I->second.begin(),
11395 OE = I->second.end();
11396 OI != OE; ++OI) {
11397 assert(OI->second.size() > 0 && "no final overrider");
11398 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011399
Richard Smithff817f72012-07-07 06:59:51 +000011400 // C++ [basic.def.odr]p2:
11401 // [...] A virtual member function is used if it is not pure. [...]
11402 if (!Overrider->isPure())
11403 MarkFunctionReferenced(Loc, Overrider);
11404 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011405 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011406
11407 // Only classes that have virtual bases need a VTT.
11408 if (RD->getNumVBases() == 0)
11409 return;
11410
11411 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11412 e = RD->bases_end(); i != e; ++i) {
11413 const CXXRecordDecl *Base =
11414 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011415 if (Base->getNumVBases() == 0)
11416 continue;
11417 MarkVirtualMembersReferenced(Loc, Base);
11418 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011419}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011420
11421/// SetIvarInitializers - This routine builds initialization ASTs for the
11422/// Objective-C implementation whose ivars need be initialized.
11423void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011424 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011425 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011426 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011427 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011428 CollectIvarsToConstructOrDestruct(OID, ivars);
11429 if (ivars.empty())
11430 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011431 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011432 for (unsigned i = 0; i < ivars.size(); i++) {
11433 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011434 if (Field->isInvalidDecl())
11435 continue;
11436
Sean Huntcbb67482011-01-08 20:30:50 +000011437 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011438 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11439 InitializationKind InitKind =
11440 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11441
11442 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011443 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011444 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011445 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011446 // Note, MemberInit could actually come back empty if no initialization
11447 // is required (e.g., because it would call a trivial default constructor)
11448 if (!MemberInit.get() || MemberInit.isInvalid())
11449 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011450
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011451 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011452 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11453 SourceLocation(),
11454 MemberInit.takeAs<Expr>(),
11455 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011456 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011457
11458 // Be sure that the destructor is accessible and is marked as referenced.
11459 if (const RecordType *RecordTy
11460 = Context.getBaseElementType(Field->getType())
11461 ->getAs<RecordType>()) {
11462 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011463 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011464 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011465 CheckDestructorAccess(Field->getLocation(), Destructor,
11466 PDiag(diag::err_access_dtor_ivar)
11467 << Context.getBaseElementType(Field->getType()));
11468 }
11469 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011470 }
11471 ObjCImplementation->setIvarInitializers(Context,
11472 AllToInit.data(), AllToInit.size());
11473 }
11474}
Sean Huntfe57eef2011-05-04 05:57:24 +000011475
Sean Huntebcbe1d2011-05-04 23:29:54 +000011476static
11477void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11478 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11479 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11480 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11481 Sema &S) {
11482 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11483 CE = Current.end();
11484 if (Ctor->isInvalidDecl())
11485 return;
11486
Richard Smitha8eaf002012-08-23 06:16:52 +000011487 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11488
11489 // Target may not be determinable yet, for instance if this is a dependent
11490 // call in an uninstantiated template.
11491 if (Target) {
11492 const FunctionDecl *FNTarget = 0;
11493 (void)Target->hasBody(FNTarget);
11494 Target = const_cast<CXXConstructorDecl*>(
11495 cast_or_null<CXXConstructorDecl>(FNTarget));
11496 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011497
11498 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11499 // Avoid dereferencing a null pointer here.
11500 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11501
11502 if (!Current.insert(Canonical))
11503 return;
11504
11505 // We know that beyond here, we aren't chaining into a cycle.
11506 if (!Target || !Target->isDelegatingConstructor() ||
11507 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11508 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11509 Valid.insert(*CI);
11510 Current.clear();
11511 // We've hit a cycle.
11512 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11513 Current.count(TCanonical)) {
11514 // If we haven't diagnosed this cycle yet, do so now.
11515 if (!Invalid.count(TCanonical)) {
11516 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011517 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011518 << Ctor;
11519
Richard Smitha8eaf002012-08-23 06:16:52 +000011520 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011521 if (TCanonical != Canonical)
11522 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11523
11524 CXXConstructorDecl *C = Target;
11525 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011526 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011527 (void)C->getTargetConstructor()->hasBody(FNTarget);
11528 assert(FNTarget && "Ctor cycle through bodiless function");
11529
Richard Smitha8eaf002012-08-23 06:16:52 +000011530 C = const_cast<CXXConstructorDecl*>(
11531 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011532 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11533 }
11534 }
11535
11536 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11537 Invalid.insert(*CI);
11538 Current.clear();
11539 } else {
11540 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11541 }
11542}
11543
11544
Sean Huntfe57eef2011-05-04 05:57:24 +000011545void Sema::CheckDelegatingCtorCycles() {
11546 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11547
Sean Huntebcbe1d2011-05-04 23:29:54 +000011548 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11549 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011550
Douglas Gregor0129b562011-07-27 21:57:17 +000011551 for (DelegatingCtorDeclsType::iterator
11552 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011553 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011554 I != E; ++I)
11555 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011556
11557 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11558 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011559}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011560
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011561namespace {
11562 /// \brief AST visitor that finds references to the 'this' expression.
11563 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11564 Sema &S;
11565
11566 public:
11567 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11568
11569 bool VisitCXXThisExpr(CXXThisExpr *E) {
11570 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11571 << E->isImplicit();
11572 return false;
11573 }
11574 };
11575}
11576
11577bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11578 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11579 if (!TSInfo)
11580 return false;
11581
11582 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011583 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011584 if (!ProtoTL)
11585 return false;
11586
11587 // C++11 [expr.prim.general]p3:
11588 // [The expression this] shall not appear before the optional
11589 // cv-qualifier-seq and it shall not appear within the declaration of a
11590 // static member function (although its type and value category are defined
11591 // within a static member function as they are within a non-static member
11592 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011593 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011594 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011595 FindCXXThisExpr Finder(*this);
11596
11597 // If the return type came after the cv-qualifier-seq, check it now.
11598 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011599 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011600 return true;
11601
11602 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011603 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11604 return true;
11605
11606 return checkThisInStaticMemberFunctionAttributes(Method);
11607}
11608
11609bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11610 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11611 if (!TSInfo)
11612 return false;
11613
11614 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011615 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011616 if (!ProtoTL)
11617 return false;
11618
David Blaikie39e6ab42013-02-18 22:06:02 +000011619 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011620 FindCXXThisExpr Finder(*this);
11621
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011622 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011623 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011624 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011625 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011626 case EST_DynamicNone:
11627 case EST_MSAny:
11628 case EST_None:
11629 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011630
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011631 case EST_ComputedNoexcept:
11632 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11633 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011634
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011635 case EST_Dynamic:
11636 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011637 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011638 E != EEnd; ++E) {
11639 if (!Finder.TraverseType(*E))
11640 return true;
11641 }
11642 break;
11643 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011644
11645 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011646}
11647
11648bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11649 FindCXXThisExpr Finder(*this);
11650
11651 // Check attributes.
11652 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11653 A != AEnd; ++A) {
11654 // FIXME: This should be emitted by tblgen.
11655 Expr *Arg = 0;
11656 ArrayRef<Expr *> Args;
11657 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11658 Arg = G->getArg();
11659 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11660 Arg = G->getArg();
11661 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11662 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11663 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11664 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11665 else if (ExclusiveLockFunctionAttr *ELF
11666 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11667 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11668 else if (SharedLockFunctionAttr *SLF
11669 = dyn_cast<SharedLockFunctionAttr>(*A))
11670 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11671 else if (ExclusiveTrylockFunctionAttr *ETLF
11672 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11673 Arg = ETLF->getSuccessValue();
11674 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11675 } else if (SharedTrylockFunctionAttr *STLF
11676 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11677 Arg = STLF->getSuccessValue();
11678 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11679 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11680 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11681 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11682 Arg = LR->getArg();
11683 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11684 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11685 else if (ExclusiveLocksRequiredAttr *ELR
11686 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11687 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11688 else if (SharedLocksRequiredAttr *SLR
11689 = dyn_cast<SharedLocksRequiredAttr>(*A))
11690 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11691
11692 if (Arg && !Finder.TraverseStmt(Arg))
11693 return true;
11694
11695 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11696 if (!Finder.TraverseStmt(Args[I]))
11697 return true;
11698 }
11699 }
11700
11701 return false;
11702}
11703
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011704void
11705Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11706 ArrayRef<ParsedType> DynamicExceptions,
11707 ArrayRef<SourceRange> DynamicExceptionRanges,
11708 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011709 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011710 FunctionProtoType::ExtProtoInfo &EPI) {
11711 Exceptions.clear();
11712 EPI.ExceptionSpecType = EST;
11713 if (EST == EST_Dynamic) {
11714 Exceptions.reserve(DynamicExceptions.size());
11715 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11716 // FIXME: Preserve type source info.
11717 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11718
11719 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11720 collectUnexpandedParameterPacks(ET, Unexpanded);
11721 if (!Unexpanded.empty()) {
11722 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11723 UPPC_ExceptionType,
11724 Unexpanded);
11725 continue;
11726 }
11727
11728 // Check that the type is valid for an exception spec, and
11729 // drop it if not.
11730 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11731 Exceptions.push_back(ET);
11732 }
11733 EPI.NumExceptions = Exceptions.size();
11734 EPI.Exceptions = Exceptions.data();
11735 return;
11736 }
11737
11738 if (EST == EST_ComputedNoexcept) {
11739 // If an error occurred, there's no expression here.
11740 if (NoexceptExpr) {
11741 assert((NoexceptExpr->isTypeDependent() ||
11742 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11743 Context.BoolTy) &&
11744 "Parser should have made sure that the expression is boolean");
11745 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11746 EPI.ExceptionSpecType = EST_BasicNoexcept;
11747 return;
11748 }
11749
11750 if (!NoexceptExpr->isValueDependent())
11751 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011752 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011753 /*AllowFold*/ false).take();
11754 EPI.NoexceptExpr = NoexceptExpr;
11755 }
11756 return;
11757 }
11758}
11759
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011760/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11761Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11762 // Implicitly declared functions (e.g. copy constructors) are
11763 // __host__ __device__
11764 if (D->isImplicit())
11765 return CFT_HostDevice;
11766
11767 if (D->hasAttr<CUDAGlobalAttr>())
11768 return CFT_Global;
11769
11770 if (D->hasAttr<CUDADeviceAttr>()) {
11771 if (D->hasAttr<CUDAHostAttr>())
11772 return CFT_HostDevice;
11773 else
11774 return CFT_Device;
11775 }
11776
11777 return CFT_Host;
11778}
11779
11780bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11781 CUDAFunctionTarget CalleeTarget) {
11782 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11783 // Callable from the device only."
11784 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11785 return true;
11786
11787 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11788 // Callable from the host only."
11789 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11790 // Callable from the host only."
11791 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11792 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11793 return true;
11794
11795 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11796 return true;
11797
11798 return false;
11799}