blob: 509a30209aad50d9de7e9fb1661d33f689ffaec9 [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);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
David Majnemerf6a144f2013-06-25 23:09:30 +0000407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410 if (!PVD->hasDefaultArg())
411 return false;
412 if (!PVD->hasInheritedDefaultArg())
413 return true;
414 }
415 return false;
416}
417
Craig Topper1a6eac82012-09-21 04:33:26 +0000418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000424 bool Invalid = false;
425
Chris Lattner3d1cee32008-04-08 05:04:30 +0000426 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // For non-template functions, default arguments can be added in
428 // later declarations of a function in the same
429 // scope. Declarations in different scopes have completely
430 // distinct sets of default arguments. That is, declarations in
431 // inner scopes do not acquire default arguments from
432 // declarations in outer scopes, and vice versa. In a given
433 // function declaration, all parameters subsequent to a
434 // parameter with a default argument shall have default
435 // arguments supplied in this or previous declarations. A
436 // default argument shall not be redefined by a later
437 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000438 //
439 // C++ [dcl.fct.default]p6:
440 // Except for member functions of class templates, the default arguments
441 // in a member function definition that appears outside of the class
442 // definition are added to the set of default arguments provided by the
443 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445 ParmVarDecl *OldParam = Old->getParamDecl(p);
446 ParmVarDecl *NewParam = New->getParamDecl(p);
447
James Molloy9cda03f2012-03-13 08:55:35 +0000448 bool OldParamHasDfl = OldParam->hasDefaultArg();
449 bool NewParamHasDfl = NewParam->hasDefaultArg();
450
451 NamedDecl *ND = Old;
452 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
453 // Ignore default parameters of old decl if they are not in
454 // the same scope.
455 OldParamHasDfl = false;
456
457 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000458
Francois Pichet8d051e02011-04-10 03:03:52 +0000459 unsigned DiagDefaultParamID =
460 diag::err_param_default_argument_redefinition;
461
462 // MSVC accepts that default parameters be redefined for member functions
463 // of template class. The new default parameter's value is ignored.
464 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000465 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000466 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
467 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000468 // Merge the old default argument into the new parameter.
469 NewParam->setHasInheritedDefaultArg();
470 if (OldParam->hasUninstantiatedDefaultArg())
471 NewParam->setUninstantiatedDefaultArg(
472 OldParam->getUninstantiatedDefaultArg());
473 else
474 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000475 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000476 Invalid = false;
477 }
478 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000479
Francois Pichet8cf90492011-04-10 04:58:30 +0000480 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
481 // hint here. Alternatively, we could walk the type-source information
482 // for NewParam to find the last source location in the type... but it
483 // isn't worth the effort right now. This is the kind of test case that
484 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000485 // int f(int);
486 // void g(int (*fp)(int) = f);
487 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000488 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000489 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000490
491 // Look for the function declaration where the default argument was
492 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000493 for (FunctionDecl *Older = Old->getPreviousDecl();
494 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 if (!Older->getParamDecl(p)->hasDefaultArg())
496 break;
497
498 OldParam = Older->getParamDecl(p);
499 }
500
501 Diag(OldParam->getLocation(), diag::note_previous_definition)
502 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000503 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000504 // Merge the old default argument into the new parameter.
505 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000506 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000507 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000508 if (OldParam->hasUninstantiatedDefaultArg())
509 NewParam->setUninstantiatedDefaultArg(
510 OldParam->getUninstantiatedDefaultArg());
511 else
John McCall3d6c1782010-05-04 01:53:42 +0000512 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000513 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000514 if (New->getDescribedFunctionTemplate()) {
515 // Paragraph 4, quoted above, only applies to non-template functions.
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_template_redecl)
518 << NewParam->getDefaultArgRange();
519 Diag(Old->getLocation(), diag::note_template_prev_declaration)
520 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000521 } else if (New->getTemplateSpecializationKind()
522 != TSK_ImplicitInstantiation &&
523 New->getTemplateSpecializationKind() != TSK_Undeclared) {
524 // C++ [temp.expr.spec]p21:
525 // Default function arguments shall not be specified in a declaration
526 // or a definition for one of the following explicit specializations:
527 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000528 // - the explicit specialization of a member function template;
529 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000530 // template where the class template specialization to which the
531 // member function specialization belongs is implicitly
532 // instantiated.
533 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
534 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
535 << New->getDeclName()
536 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000537 } else if (New->getDeclContext()->isDependentContext()) {
538 // C++ [dcl.fct.default]p6 (DR217):
539 // Default arguments for a member function of a class template shall
540 // be specified on the initial declaration of the member function
541 // within the class template.
542 //
543 // Reading the tea leaves a bit in DR217 and its reference to DR205
544 // leads me to the conclusion that one cannot add default function
545 // arguments for an out-of-line definition of a member function of a
546 // dependent type.
547 int WhichKind = 2;
548 if (CXXRecordDecl *Record
549 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
550 if (Record->getDescribedClassTemplate())
551 WhichKind = 0;
552 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
553 WhichKind = 1;
554 else
555 WhichKind = 2;
556 }
557
558 Diag(NewParam->getLocation(),
559 diag::err_param_default_argument_member_template_redecl)
560 << WhichKind
561 << NewParam->getDefaultArgRange();
562 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000563 }
564 }
565
Richard Smithb8abff62012-11-28 03:45:24 +0000566 // DR1344: If a default argument is added outside a class definition and that
567 // default argument makes the function a special member function, the program
568 // is ill-formed. This can only happen for constructors.
569 if (isa<CXXConstructorDecl>(New) &&
570 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
571 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
572 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
573 if (NewSM != OldSM) {
574 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
575 assert(NewParam->hasDefaultArg());
576 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
577 << NewParam->getDefaultArgRange() << NewSM;
578 Diag(Old->getLocation(), diag::note_previous_declaration);
579 }
580 }
581
Richard Smithff234882012-02-20 23:28:05 +0000582 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000583 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000584 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000585 if (New->isConstexpr() != Old->isConstexpr()) {
586 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
587 << New << New->isConstexpr();
588 Diag(Old->getLocation(), diag::note_previous_declaration);
589 Invalid = true;
590 }
591
David Majnemerf6a144f2013-06-25 23:09:30 +0000592 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000593 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000594 // the only declaration of the function or function template in the
595 // translation unit.
596 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
597 functionDeclHasDefaultArgument(Old)) {
598 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
599 Diag(Old->getLocation(), diag::note_previous_declaration);
600 Invalid = true;
601 }
602
Douglas Gregore13ad832010-02-12 07:32:17 +0000603 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000604 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605
Douglas Gregorcda9c672009-02-16 17:45:42 +0000606 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000607}
608
Sebastian Redl60618fa2011-03-12 11:50:43 +0000609/// \brief Merge the exception specifications of two variable declarations.
610///
611/// This is called when there's a redeclaration of a VarDecl. The function
612/// checks if the redeclaration might have an exception specification and
613/// validates compatibility and merges the specs if necessary.
614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
615 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000616 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000617 return;
618
619 assert(Context.hasSameType(New->getType(), Old->getType()) &&
620 "Should only be called if types are otherwise the same.");
621
622 QualType NewType = New->getType();
623 QualType OldType = Old->getType();
624
625 // We're only interested in pointers and references to functions, as well
626 // as pointers to member functions.
627 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
628 NewType = R->getPointeeType();
629 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
630 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
631 NewType = P->getPointeeType();
632 OldType = OldType->getAs<PointerType>()->getPointeeType();
633 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
634 NewType = M->getPointeeType();
635 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
636 }
637
638 if (!NewType->isFunctionProtoType())
639 return;
640
641 // There's lots of special cases for functions. For function pointers, system
642 // libraries are hopefully not as broken so that we don't need these
643 // workarounds.
644 if (CheckEquivalentExceptionSpec(
645 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
646 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
647 New->setInvalidDecl();
648 }
649}
650
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651/// CheckCXXDefaultArguments - Verify that the default arguments for a
652/// function declaration are well-formed according to C++
653/// [dcl.fct.default].
654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
655 unsigned NumParams = FD->getNumParams();
656 unsigned p;
657
658 // Find first parameter with a default argument
659 for (p = 0; p < NumParams; ++p) {
660 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000661 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000662 break;
663 }
664
665 // C++ [dcl.fct.default]p4:
666 // In a given function declaration, all parameters
667 // subsequent to a parameter with a default argument shall
668 // have default arguments supplied in this or previous
669 // declarations. A default argument shall not be redefined
670 // by a later declaration (not even to the same value).
671 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000672 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000674 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000675 if (Param->isInvalidDecl())
676 /* We already complained about this parameter. */;
677 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000678 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000680 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000681 else
Mike Stump1eb44332009-09-09 15:08:12 +0000682 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000683 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner3d1cee32008-04-08 05:04:30 +0000685 LastMissingDefaultArg = p;
686 }
687 }
688
689 if (LastMissingDefaultArg > 0) {
690 // Some default arguments were missing. Clear out all of the
691 // default arguments up to (and including) the last missing
692 // default argument, so that we leave the function parameters
693 // in a semantically valid state.
694 for (p = 0; p <= LastMissingDefaultArg; ++p) {
695 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000696 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000697 Param->setDefaultArg(0);
698 }
699 }
700 }
701}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000702
Richard Smith9f569cc2011-10-01 02:31:28 +0000703// CheckConstexprParameterTypes - Check whether a function's parameter types
704// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// diagnostic and return false.
706static bool CheckConstexprParameterTypes(Sema &SemaRef,
707 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000708 unsigned ArgIndex = 0;
709 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
710 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
711 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
712 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
713 SourceLocation ParamLoc = PD->getLocation();
714 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000715 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000716 diag::err_constexpr_non_literal_param,
717 ArgIndex+1, PD->getSourceRange(),
718 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000719 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 }
Joao Matos17d35c32012-08-31 22:18:20 +0000721 return true;
722}
723
724/// \brief Get diagnostic %select index for tag kind for
725/// record diagnostic message.
726/// WARNING: Indexes apply to particular diagnostics only!
727///
728/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000730 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000731 case TTK_Struct: return 0;
732 case TTK_Interface: return 1;
733 case TTK_Class: return 2;
734 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000735 }
Joao Matos17d35c32012-08-31 22:18:20 +0000736}
737
738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
739// the requirements of a constexpr function definition or a constexpr
740// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000741// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000742//
Richard Smith86c3ae42012-02-13 03:54:03 +0000743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000745 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
746 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000747 // C++11 [dcl.constexpr]p4:
748 // The definition of a constexpr constructor shall satisfy the following
749 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000750 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000751 const CXXRecordDecl *RD = MD->getParent();
752 if (RD->getNumVBases()) {
753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
754 << isa<CXXConstructorDecl>(NewFD)
755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
756 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
757 E = RD->vbases_end(); I != E; ++I)
758 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000759 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000760 return false;
761 }
Richard Smith35340502012-01-13 04:54:00 +0000762 }
763
764 if (!isa<CXXConstructorDecl>(NewFD)) {
765 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000766 // The definition of a constexpr function shall satisfy the following
767 // constraints:
768 // - it shall not be virtual;
769 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
770 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000772
Richard Smith86c3ae42012-02-13 03:54:03 +0000773 // If it's not obvious why this function is virtual, find an overridden
774 // function which uses the 'virtual' keyword.
775 const CXXMethodDecl *WrittenVirtual = Method;
776 while (!WrittenVirtual->isVirtualAsWritten())
777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
778 if (WrittenVirtual != Method)
779 Diag(WrittenVirtual->getLocation(),
780 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000781 return false;
782 }
783
784 // - its return type shall be a literal type;
785 QualType RT = NewFD->getResultType();
786 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000787 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000788 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000789 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 }
791
Richard Smith35340502012-01-13 04:54:00 +0000792 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000793 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000794 return false;
795
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 return true;
797}
798
799/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000801///
Richard Smitha10b9782013-04-22 15:31:51 +0000802/// \return true if the body is OK (maybe only as an extension), false if we
803/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000805 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
806 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000807 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
808 // contain only
809 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
810 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
811 switch ((*DclIt)->getKind()) {
812 case Decl::StaticAssert:
813 case Decl::Using:
814 case Decl::UsingShadow:
815 case Decl::UsingDirective:
816 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000817 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000818 // - static_assert-declarations
819 // - using-declarations,
820 // - using-directives,
821 continue;
822
823 case Decl::Typedef:
824 case Decl::TypeAlias: {
825 // - typedef declarations and alias-declarations that do not define
826 // classes or enumerations,
827 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
828 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
829 // Don't allow variably-modified types in constexpr functions.
830 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
831 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
832 << TL.getSourceRange() << TL.getType()
833 << isa<CXXConstructorDecl>(Dcl);
834 return false;
835 }
836 continue;
837 }
838
839 case Decl::Enum:
840 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000841 // C++1y allows types to be defined, not just declared.
842 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
843 SemaRef.Diag(DS->getLocStart(),
844 SemaRef.getLangOpts().CPlusPlus1y
845 ? diag::warn_cxx11_compat_constexpr_type_definition
846 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 continue;
849
Richard Smitha10b9782013-04-22 15:31:51 +0000850 case Decl::EnumConstant:
851 case Decl::IndirectField:
852 case Decl::ParmVar:
853 // These can only appear with other declarations which are banned in
854 // C++11 and permitted in C++1y, so ignore them.
855 continue;
856
857 case Decl::Var: {
858 // C++1y [dcl.constexpr]p3 allows anything except:
859 // a definition of a variable of non-literal type or of static or
860 // thread storage duration or for which no initialization is performed.
861 VarDecl *VD = cast<VarDecl>(*DclIt);
862 if (VD->isThisDeclarationADefinition()) {
863 if (VD->isStaticLocal()) {
864 SemaRef.Diag(VD->getLocation(),
865 diag::err_constexpr_local_var_static)
866 << isa<CXXConstructorDecl>(Dcl)
867 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
868 return false;
869 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000870 if (!VD->getType()->isDependentType() &&
871 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000872 VD->getLocation(), VD->getType(),
873 diag::err_constexpr_local_var_non_literal_type,
874 isa<CXXConstructorDecl>(Dcl)))
875 return false;
876 if (!VD->hasInit()) {
877 SemaRef.Diag(VD->getLocation(),
878 diag::err_constexpr_local_var_no_init)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883 SemaRef.Diag(VD->getLocation(),
884 SemaRef.getLangOpts().CPlusPlus1y
885 ? diag::warn_cxx11_compat_constexpr_local_var
886 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000888 continue;
889 }
890
891 case Decl::NamespaceAlias:
892 case Decl::Function:
893 // These are disallowed in C++11 and permitted in C++1y. Allow them
894 // everywhere as an extension.
895 if (!Cxx1yLoc.isValid())
896 Cxx1yLoc = DS->getLocStart();
897 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000898
899 default:
900 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904 }
905
906 return true;
907}
908
909/// Check that the given field is initialized within a constexpr constructor.
910///
911/// \param Dcl The constexpr constructor being checked.
912/// \param Field The field being checked. This may be a member of an anonymous
913/// struct or union nested within the class being checked.
914/// \param Inits All declarations, including anonymous struct/union members and
915/// indirect members, for which any initialization was provided.
916/// \param Diagnosed Set to true if an error is produced.
917static void CheckConstexprCtorInitializer(Sema &SemaRef,
918 const FunctionDecl *Dcl,
919 FieldDecl *Field,
920 llvm::SmallSet<Decl*, 16> &Inits,
921 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000922 if (Field->isInvalidDecl())
923 return;
924
Douglas Gregord61db332011-10-10 17:22:13 +0000925 if (Field->isUnnamedBitfield())
926 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000927
928 if (Field->isAnonymousStructOrUnion() &&
929 Field->getType()->getAsCXXRecordDecl()->isEmpty())
930 return;
931
Richard Smith9f569cc2011-10-01 02:31:28 +0000932 if (!Inits.count(Field)) {
933 if (!Diagnosed) {
934 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
935 Diagnosed = true;
936 }
937 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
938 } else if (Field->isAnonymousStructOrUnion()) {
939 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
940 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
941 I != E; ++I)
942 // If an anonymous union contains an anonymous struct of which any member
943 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000944 if (!RD->isUnion() || Inits.count(*I))
945 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 }
947}
948
Richard Smitha10b9782013-04-22 15:31:51 +0000949/// Check the provided statement is allowed in a constexpr function
950/// definition.
951static bool
952CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
953 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
954 SourceLocation &Cxx1yLoc) {
955 // - its function-body shall be [...] a compound-statement that contains only
956 switch (S->getStmtClass()) {
957 case Stmt::NullStmtClass:
958 // - null statements,
959 return true;
960
961 case Stmt::DeclStmtClass:
962 // - static_assert-declarations
963 // - using-declarations,
964 // - using-directives,
965 // - typedef declarations and alias-declarations that do not define
966 // classes or enumerations,
967 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
968 return false;
969 return true;
970
971 case Stmt::ReturnStmtClass:
972 // - and exactly one return statement;
973 if (isa<CXXConstructorDecl>(Dcl)) {
974 // C++1y allows return statements in constexpr constructors.
975 if (!Cxx1yLoc.isValid())
976 Cxx1yLoc = S->getLocStart();
977 return true;
978 }
979
980 ReturnStmts.push_back(S->getLocStart());
981 return true;
982
983 case Stmt::CompoundStmtClass: {
984 // C++1y allows compound-statements.
985 if (!Cxx1yLoc.isValid())
986 Cxx1yLoc = S->getLocStart();
987
988 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
989 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
990 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
991 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
992 Cxx1yLoc))
993 return false;
994 }
995 return true;
996 }
997
998 case Stmt::AttributedStmtClass:
999 if (!Cxx1yLoc.isValid())
1000 Cxx1yLoc = S->getLocStart();
1001 return true;
1002
1003 case Stmt::IfStmtClass: {
1004 // C++1y allows if-statements.
1005 if (!Cxx1yLoc.isValid())
1006 Cxx1yLoc = S->getLocStart();
1007
1008 IfStmt *If = cast<IfStmt>(S);
1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1010 Cxx1yLoc))
1011 return false;
1012 if (If->getElse() &&
1013 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1014 Cxx1yLoc))
1015 return false;
1016 return true;
1017 }
1018
1019 case Stmt::WhileStmtClass:
1020 case Stmt::DoStmtClass:
1021 case Stmt::ForStmtClass:
1022 case Stmt::CXXForRangeStmtClass:
1023 case Stmt::ContinueStmtClass:
1024 // C++1y allows all of these. We don't allow them as extensions in C++11,
1025 // because they don't make sense without variable mutation.
1026 if (!SemaRef.getLangOpts().CPlusPlus1y)
1027 break;
1028 if (!Cxx1yLoc.isValid())
1029 Cxx1yLoc = S->getLocStart();
1030 for (Stmt::child_range Children = S->children(); Children; ++Children)
1031 if (*Children &&
1032 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1033 Cxx1yLoc))
1034 return false;
1035 return true;
1036
1037 case Stmt::SwitchStmtClass:
1038 case Stmt::CaseStmtClass:
1039 case Stmt::DefaultStmtClass:
1040 case Stmt::BreakStmtClass:
1041 // C++1y allows switch-statements, and since they don't need variable
1042 // mutation, we can reasonably allow them in C++11 as an extension.
1043 if (!Cxx1yLoc.isValid())
1044 Cxx1yLoc = S->getLocStart();
1045 for (Stmt::child_range Children = S->children(); Children; ++Children)
1046 if (*Children &&
1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048 Cxx1yLoc))
1049 return false;
1050 return true;
1051
1052 default:
1053 if (!isa<Expr>(S))
1054 break;
1055
1056 // C++1y allows expression-statements.
1057 if (!Cxx1yLoc.isValid())
1058 Cxx1yLoc = S->getLocStart();
1059 return true;
1060 }
1061
1062 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1063 << isa<CXXConstructorDecl>(Dcl);
1064 return false;
1065}
1066
Richard Smith9f569cc2011-10-01 02:31:28 +00001067/// Check the body for the given constexpr function declaration only contains
1068/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1069///
1070/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001071bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001073 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001074 // The definition of a constexpr function shall satisfy the following
1075 // constraints: [...]
1076 // - its function-body shall be = delete, = default, or a
1077 // compound-statement
1078 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001079 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001080 // In the definition of a constexpr constructor, [...]
1081 // - its function-body shall not be a function-try-block;
1082 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1083 << isa<CXXConstructorDecl>(Dcl);
1084 return false;
1085 }
1086
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001087 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001088
1089 // - its function-body shall be [...] a compound-statement that contains only
1090 // [... list of cases ...]
1091 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1092 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001093 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1094 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001095 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1096 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 }
1098
Richard Smitha10b9782013-04-22 15:31:51 +00001099 if (Cxx1yLoc.isValid())
1100 Diag(Cxx1yLoc,
1101 getLangOpts().CPlusPlus1y
1102 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1103 : diag::ext_constexpr_body_invalid_stmt)
1104 << isa<CXXConstructorDecl>(Dcl);
1105
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 if (const CXXConstructorDecl *Constructor
1107 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1108 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001109 // DR1359:
1110 // - every non-variant non-static data member and base class sub-object
1111 // shall be initialized;
1112 // - if the class is a non-empty union, or for each non-empty anonymous
1113 // union member of a non-union class, exactly one non-static data member
1114 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001115 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001116 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001117 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1118 return false;
1119 }
Richard Smith6e433752011-10-10 16:38:04 +00001120 } else if (!Constructor->isDependentContext() &&
1121 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001122 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1123
1124 // Skip detailed checking if we have enough initializers, and we would
1125 // allow at most one initializer per member.
1126 bool AnyAnonStructUnionMembers = false;
1127 unsigned Fields = 0;
1128 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1129 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001130 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001131 AnyAnonStructUnionMembers = true;
1132 break;
1133 }
1134 }
1135 if (AnyAnonStructUnionMembers ||
1136 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1137 // Check initialization of non-static data members. Base classes are
1138 // always initialized so do not need to be checked. Dependent bases
1139 // might not have initializers in the member initializer list.
1140 llvm::SmallSet<Decl*, 16> Inits;
1141 for (CXXConstructorDecl::init_const_iterator
1142 I = Constructor->init_begin(), E = Constructor->init_end();
1143 I != E; ++I) {
1144 if (FieldDecl *FD = (*I)->getMember())
1145 Inits.insert(FD);
1146 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1147 Inits.insert(ID->chain_begin(), ID->chain_end());
1148 }
1149
1150 bool Diagnosed = false;
1151 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1152 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001153 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001154 if (Diagnosed)
1155 return false;
1156 }
1157 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001158 } else {
1159 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001160 // C++1y doesn't require constexpr functions to contain a 'return'
1161 // statement. We still do, unless the return type is void, because
1162 // otherwise if there's no return statement, the function cannot
1163 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001164 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001165 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001166 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1167 : diag::err_constexpr_body_no_return);
1168 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001169 }
1170 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001171 Diag(ReturnStmts.back(),
1172 getLangOpts().CPlusPlus1y
1173 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1174 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1176 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001177 }
1178 }
1179
Richard Smith5ba73e12012-02-04 00:33:54 +00001180 // C++11 [dcl.constexpr]p5:
1181 // if no function argument values exist such that the function invocation
1182 // substitution would produce a constant expression, the program is
1183 // ill-formed; no diagnostic required.
1184 // C++11 [dcl.constexpr]p3:
1185 // - every constructor call and implicit conversion used in initializing the
1186 // return value shall be one of those allowed in a constant expression.
1187 // C++11 [dcl.constexpr]p4:
1188 // - every constructor involved in initializing non-static data members and
1189 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001190 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001191 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001192 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001193 << isa<CXXConstructorDecl>(Dcl);
1194 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1195 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001196 // Don't return false here: we allow this for compatibility in
1197 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001198 }
1199
Richard Smith9f569cc2011-10-01 02:31:28 +00001200 return true;
1201}
1202
Douglas Gregorb48fe382008-10-31 09:07:45 +00001203/// isCurrentClassName - Determine whether the identifier II is the
1204/// name of the class type currently being defined. In the case of
1205/// nested classes, this will only return true if II is the name of
1206/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001207bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1208 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001210
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001211 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001212 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001213 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001214 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1215 } else
1216 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1217
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001218 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001219 return &II == CurDecl->getIdentifier();
1220 else
1221 return false;
1222}
1223
Douglas Gregor229d47a2012-11-10 07:24:09 +00001224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227 const CXXRecordDecl *Current) {
1228 SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230 Class = Class->getCanonicalDecl();
1231 while (true) {
1232 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233 E = Current->bases_end();
1234 I != E; ++I) {
1235 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236 if (!Base)
1237 continue;
1238
1239 Base = Base->getDefinition();
1240 if (!Base)
1241 continue;
1242
1243 if (Base->getCanonicalDecl() == Class)
1244 return true;
1245
1246 Queue.push_back(Base);
1247 }
1248
1249 if (Queue.empty())
1250 return false;
1251
1252 Current = Queue.back();
1253 Queue.pop_back();
1254 }
1255
1256 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001257}
1258
Mike Stump1eb44332009-09-09 15:08:12 +00001259/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260///
1261/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1262/// and returns NULL otherwise.
1263CXXBaseSpecifier *
1264Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1265 SourceRange SpecifierRange,
1266 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001267 TypeSourceInfo *TInfo,
1268 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001269 QualType BaseType = TInfo->getType();
1270
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271 // C++ [class.union]p1:
1272 // A union shall not have base classes.
1273 if (Class->isUnion()) {
1274 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1275 << SpecifierRange;
1276 return 0;
1277 }
1278
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001279 if (EllipsisLoc.isValid() &&
1280 !TInfo->getType()->containsUnexpandedParameterPack()) {
1281 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1282 << TInfo->getTypeLoc().getSourceRange();
1283 EllipsisLoc = SourceLocation();
1284 }
Douglas Gregord777e282012-11-10 01:18:17 +00001285
1286 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1287
1288 if (BaseType->isDependentType()) {
1289 // Make sure that we don't have circular inheritance among our dependent
1290 // bases. For non-dependent bases, the check for completeness below handles
1291 // this.
1292 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1293 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1294 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001295 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001296 Diag(BaseLoc, diag::err_circular_inheritance)
1297 << BaseType << Context.getTypeDeclType(Class);
1298
1299 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1300 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1301 << BaseType;
1302
1303 return 0;
1304 }
1305 }
1306
Mike Stump1eb44332009-09-09 15:08:12 +00001307 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001308 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001309 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001310 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311
1312 // Base specifiers must be record types.
1313 if (!BaseType->isRecordType()) {
1314 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1315 return 0;
1316 }
1317
1318 // C++ [class.union]p1:
1319 // A union shall not be used as a base class.
1320 if (BaseType->isUnionType()) {
1321 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1322 return 0;
1323 }
1324
1325 // C++ [class.derived]p2:
1326 // The class-name in a base-specifier shall not be an incompletely
1327 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001328 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001329 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001330 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001331 return 0;
John McCall572fc622010-08-17 07:23:57 +00001332 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001333
Eli Friedman1d954f62009-08-15 21:55:26 +00001334 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001335 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001336 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001337 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001338 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001339 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001340 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001341
Anders Carlsson1d209272011-03-25 14:55:14 +00001342 // C++ [class]p3:
1343 // If a class is marked final and it appears as a base-type-specifier in
1344 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001345 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001346 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1347 << CXXBaseDecl->getDeclName();
1348 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1349 << CXXBaseDecl->getDeclName();
1350 return 0;
1351 }
1352
John McCall572fc622010-08-17 07:23:57 +00001353 if (BaseDecl->isInvalidDecl())
1354 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001355
1356 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001357 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001358 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001359 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001360}
1361
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001362/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1363/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001364/// example:
1365/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001366/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001367BaseResult
John McCalld226f652010-08-21 09:40:31 +00001368Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001369 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001370 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001371 ParsedType basetype, SourceLocation BaseLoc,
1372 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001373 if (!classdecl)
1374 return true;
1375
Douglas Gregor40808ce2009-03-09 23:48:35 +00001376 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001377 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001378 if (!Class)
1379 return true;
1380
Richard Smith05321402013-02-19 23:47:15 +00001381 // We do not support any C++11 attributes on base-specifiers yet.
1382 // Diagnose any attributes we see.
1383 if (!Attributes.empty()) {
1384 for (AttributeList *Attr = Attributes.getList(); Attr;
1385 Attr = Attr->getNext()) {
1386 if (Attr->isInvalid() ||
1387 Attr->getKind() == AttributeList::IgnoredAttribute)
1388 continue;
1389 Diag(Attr->getLoc(),
1390 Attr->getKind() == AttributeList::UnknownAttribute
1391 ? diag::warn_unknown_attribute_ignored
1392 : diag::err_base_specifier_attribute)
1393 << Attr->getName();
1394 }
1395 }
1396
Nick Lewycky56062202010-07-26 16:56:01 +00001397 TypeSourceInfo *TInfo = 0;
1398 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001399
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001400 if (EllipsisLoc.isInvalid() &&
1401 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001402 UPPC_BaseType))
1403 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001404
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001406 Virtual, Access, TInfo,
1407 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001409 else
1410 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregor2943aed2009-03-03 04:44:36 +00001412 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001414
Douglas Gregor2943aed2009-03-03 04:44:36 +00001415/// \brief Performs the actual work of attaching the given base class
1416/// specifiers to a C++ class.
1417bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1418 unsigned NumBases) {
1419 if (NumBases == 0)
1420 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001421
1422 // Used to keep track of which base types we have already seen, so
1423 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001424 // that the key is always the unqualified canonical type of the base
1425 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1427
1428 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001429 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001430 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001431 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001432 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001433 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001434 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001435
1436 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1437 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001438 // C++ [class.mi]p3:
1439 // A class shall not be specified as a direct base class of a
1440 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001441 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001443 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001444 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001445
1446 // Delete the duplicate base class specifier; we're going to
1447 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001448 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001449
1450 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001451 } else {
1452 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001453 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001454 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001455 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1456 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1457 if (Class->isInterface() &&
1458 (!RD->isInterface() ||
1459 KnownBase->getAccessSpecifier() != AS_public)) {
1460 // The Microsoft extension __interface does not permit bases that
1461 // are not themselves public interfaces.
1462 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1463 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1464 << RD->getSourceRange();
1465 Invalid = true;
1466 }
1467 if (RD->hasAttr<WeakAttr>())
1468 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1469 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001470 }
1471 }
1472
1473 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001474 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001475
1476 // Delete the remaining (good) base class specifiers, since their
1477 // data has been copied into the CXXRecordDecl.
1478 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001479 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480
1481 return Invalid;
1482}
1483
1484/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1485/// class, after checking whether there are any duplicate base
1486/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001487void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001488 unsigned NumBases) {
1489 if (!ClassDecl || !Bases || !NumBases)
1490 return;
1491
1492 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001493 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001494}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001495
Douglas Gregora8f32e02009-10-06 17:59:45 +00001496/// \brief Determine whether the type \p Derived is a C++ class that is
1497/// derived from the type \p Base.
1498bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001499 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001500 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001501
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001502 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001503 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001504 return false;
1505
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001506 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001507 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001508 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001509
1510 // If either the base or the derived type is invalid, don't try to
1511 // check whether one is derived from the other.
1512 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1513 return false;
1514
John McCall86ff3082010-02-04 22:26:26 +00001515 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1516 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001517}
1518
1519/// \brief Determine whether the type \p Derived is a C++ class that is
1520/// derived from the type \p Base.
1521bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001522 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001523 return false;
1524
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001525 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001526 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001527 return false;
1528
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001529 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001530 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001531 return false;
1532
Douglas Gregora8f32e02009-10-06 17:59:45 +00001533 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1534}
1535
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001536void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001537 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001538 assert(BasePathArray.empty() && "Base path array must be empty!");
1539 assert(Paths.isRecordingPaths() && "Must record paths!");
1540
1541 const CXXBasePath &Path = Paths.front();
1542
1543 // We first go backward and check if we have a virtual base.
1544 // FIXME: It would be better if CXXBasePath had the base specifier for
1545 // the nearest virtual base.
1546 unsigned Start = 0;
1547 for (unsigned I = Path.size(); I != 0; --I) {
1548 if (Path[I - 1].Base->isVirtual()) {
1549 Start = I - 1;
1550 break;
1551 }
1552 }
1553
1554 // Now add all bases.
1555 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001556 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001557}
1558
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001559/// \brief Determine whether the given base path includes a virtual
1560/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001561bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1562 for (CXXCastPath::const_iterator B = BasePath.begin(),
1563 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001564 B != BEnd; ++B)
1565 if ((*B)->isVirtual())
1566 return true;
1567
1568 return false;
1569}
1570
Douglas Gregora8f32e02009-10-06 17:59:45 +00001571/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1572/// conversion (where Derived and Base are class types) is
1573/// well-formed, meaning that the conversion is unambiguous (and
1574/// that all of the base classes are accessible). Returns true
1575/// and emits a diagnostic if the code is ill-formed, returns false
1576/// otherwise. Loc is the location where this routine should point to
1577/// if there is an error, and Range is the source range to highlight
1578/// if there is an error.
1579bool
1580Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001581 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001582 unsigned AmbigiousBaseConvID,
1583 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001585 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001586 // First, determine whether the path from Derived to Base is
1587 // ambiguous. This is slightly more expensive than checking whether
1588 // the Derived to Base conversion exists, because here we need to
1589 // explore multiple paths to determine if there is an ambiguity.
1590 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1591 /*DetectVirtual=*/false);
1592 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1593 assert(DerivationOkay &&
1594 "Can only be used with a derived-to-base conversion");
1595 (void)DerivationOkay;
1596
1597 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001598 if (InaccessibleBaseID) {
1599 // Check that the base class can be accessed.
1600 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1601 InaccessibleBaseID)) {
1602 case AR_inaccessible:
1603 return true;
1604 case AR_accessible:
1605 case AR_dependent:
1606 case AR_delayed:
1607 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001608 }
John McCall6b2accb2010-02-10 09:31:12 +00001609 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001610
1611 // Build a base path if necessary.
1612 if (BasePath)
1613 BuildBasePathArray(Paths, *BasePath);
1614 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001615 }
1616
David Majnemer2f686692013-06-22 06:43:58 +00001617 if (AmbigiousBaseConvID) {
1618 // We know that the derived-to-base conversion is ambiguous, and
1619 // we're going to produce a diagnostic. Perform the derived-to-base
1620 // search just one more time to compute all of the possible paths so
1621 // that we can print them out. This is more expensive than any of
1622 // the previous derived-to-base checks we've done, but at this point
1623 // performance isn't as much of an issue.
1624 Paths.clear();
1625 Paths.setRecordingPaths(true);
1626 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1627 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1628 (void)StillOkay;
1629
1630 // Build up a textual representation of the ambiguous paths, e.g.,
1631 // D -> B -> A, that will be used to illustrate the ambiguous
1632 // conversions in the diagnostic. We only print one of the paths
1633 // to each base class subobject.
1634 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1635
1636 Diag(Loc, AmbigiousBaseConvID)
1637 << Derived << Base << PathDisplayStr << Range << Name;
1638 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001639 return true;
1640}
1641
1642bool
1643Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001644 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001645 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001646 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001648 IgnoreAccess ? 0
1649 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001650 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001651 Loc, Range, DeclarationName(),
1652 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001653}
1654
1655
1656/// @brief Builds a string representing ambiguous paths from a
1657/// specific derived class to different subobjects of the same base
1658/// class.
1659///
1660/// This function builds a string that can be used in error messages
1661/// to show the different paths that one can take through the
1662/// inheritance hierarchy to go from the derived class to different
1663/// subobjects of a base class. The result looks something like this:
1664/// @code
1665/// struct D -> struct B -> struct A
1666/// struct D -> struct C -> struct A
1667/// @endcode
1668std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1669 std::string PathDisplayStr;
1670 std::set<unsigned> DisplayedPaths;
1671 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1672 Path != Paths.end(); ++Path) {
1673 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1674 // We haven't displayed a path to this particular base
1675 // class subobject yet.
1676 PathDisplayStr += "\n ";
1677 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1678 for (CXXBasePath::const_iterator Element = Path->begin();
1679 Element != Path->end(); ++Element)
1680 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1681 }
1682 }
1683
1684 return PathDisplayStr;
1685}
1686
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001687//===----------------------------------------------------------------------===//
1688// C++ class member Handling
1689//===----------------------------------------------------------------------===//
1690
Abramo Bagnara6206d532010-06-05 05:09:32 +00001691/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001692bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1693 SourceLocation ASLoc,
1694 SourceLocation ColonLoc,
1695 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001696 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001697 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001698 ASLoc, ColonLoc);
1699 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001700 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001701}
1702
Richard Smitha4b39652012-08-06 03:25:17 +00001703/// CheckOverrideControl - Check C++11 override control semantics.
1704void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001705 if (D->isInvalidDecl())
1706 return;
1707
Chris Lattner5f9e2722011-07-23 10:55:15 +00001708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001709
Richard Smitha4b39652012-08-06 03:25:17 +00001710 // Do we know which functions this declaration might be overriding?
1711 bool OverridesAreKnown = !MD ||
1712 (!MD->getParent()->hasAnyDependentBases() &&
1713 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001714
Richard Smitha4b39652012-08-06 03:25:17 +00001715 if (!MD || !MD->isVirtual()) {
1716 if (OverridesAreKnown) {
1717 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1718 Diag(OA->getLocation(),
1719 diag::override_keyword_only_allowed_on_virtual_member_functions)
1720 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1721 D->dropAttr<OverrideAttr>();
1722 }
1723 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1724 Diag(FA->getLocation(),
1725 diag::override_keyword_only_allowed_on_virtual_member_functions)
1726 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1727 D->dropAttr<FinalAttr>();
1728 }
1729 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001730 return;
1731 }
Richard Smitha4b39652012-08-06 03:25:17 +00001732
1733 if (!OverridesAreKnown)
1734 return;
1735
1736 // C++11 [class.virtual]p5:
1737 // If a virtual function is marked with the virt-specifier override and
1738 // does not override a member function of a base class, the program is
1739 // ill-formed.
1740 bool HasOverriddenMethods =
1741 MD->begin_overridden_methods() != MD->end_overridden_methods();
1742 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1743 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1744 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001745}
1746
Richard Smitha4b39652012-08-06 03:25:17 +00001747/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001748/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001749/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001750bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1751 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001752 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001753 return false;
1754
1755 Diag(New->getLocation(), diag::err_final_function_overridden)
1756 << New->getDeclName();
1757 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1758 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001759}
1760
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001761static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001762 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1763 // FIXME: Destruction of ObjC lifetime types has side-effects.
1764 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1765 return !RD->isCompleteDefinition() ||
1766 !RD->hasTrivialDefaultConstructor() ||
1767 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001768 return false;
1769}
1770
John McCall76da55d2013-04-16 07:28:30 +00001771static AttributeList *getMSPropertyAttr(AttributeList *list) {
1772 for (AttributeList* it = list; it != 0; it = it->getNext())
1773 if (it->isDeclspecPropertyAttribute())
1774 return it;
1775 return 0;
1776}
1777
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001778/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1779/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001780/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001781/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1782/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001783NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001784Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001785 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001786 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001787 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001788 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001789 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1790 DeclarationName Name = NameInfo.getName();
1791 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001792
1793 // For anonymous bitfields, the location should point to the type.
1794 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001795 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001796
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001798
John McCall4bde1e12010-06-04 08:34:12 +00001799 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001800 assert(!DS.isFriendSpecified());
1801
Richard Smith1ab0d902011-06-25 02:28:38 +00001802 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001803
John McCalle402e722012-09-25 07:32:39 +00001804 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1805 // The Microsoft extension __interface only permits public member functions
1806 // and prohibits constructors, destructors, operators, non-public member
1807 // functions, static methods and data members.
1808 unsigned InvalidDecl;
1809 bool ShowDeclName = true;
1810 if (!isFunc)
1811 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1812 else if (AS != AS_public)
1813 InvalidDecl = 2;
1814 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1815 InvalidDecl = 3;
1816 else switch (Name.getNameKind()) {
1817 case DeclarationName::CXXConstructorName:
1818 InvalidDecl = 4;
1819 ShowDeclName = false;
1820 break;
1821
1822 case DeclarationName::CXXDestructorName:
1823 InvalidDecl = 5;
1824 ShowDeclName = false;
1825 break;
1826
1827 case DeclarationName::CXXOperatorName:
1828 case DeclarationName::CXXConversionFunctionName:
1829 InvalidDecl = 6;
1830 break;
1831
1832 default:
1833 InvalidDecl = 0;
1834 break;
1835 }
1836
1837 if (InvalidDecl) {
1838 if (ShowDeclName)
1839 Diag(Loc, diag::err_invalid_member_in_interface)
1840 << (InvalidDecl-1) << Name;
1841 else
1842 Diag(Loc, diag::err_invalid_member_in_interface)
1843 << (InvalidDecl-1) << "";
1844 return 0;
1845 }
1846 }
1847
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001848 // C++ 9.2p6: A member shall not be declared to have automatic storage
1849 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001850 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1851 // data members and cannot be applied to names declared const or static,
1852 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001853 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001854 case DeclSpec::SCS_unspecified:
1855 case DeclSpec::SCS_typedef:
1856 case DeclSpec::SCS_static:
1857 break;
1858 case DeclSpec::SCS_mutable:
1859 if (isFunc) {
1860 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Richard Smithec642442013-04-12 22:46:28 +00001862 // FIXME: It would be nicer if the keyword was ignored only for this
1863 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001864 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001865 }
1866 break;
1867 default:
1868 Diag(DS.getStorageClassSpecLoc(),
1869 diag::err_storageclass_invalid_for_member);
1870 D.getMutableDeclSpec().ClearStorageClassSpecs();
1871 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001872 }
1873
Sebastian Redl669d5d72008-11-14 23:42:31 +00001874 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1875 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001876 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001877
David Blaikie1d87fba2013-01-30 01:22:18 +00001878 if (DS.isConstexprSpecified() && isInstField) {
1879 SemaDiagnosticBuilder B =
1880 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1881 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1882 if (InitStyle == ICIS_NoInit) {
1883 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1884 D.getMutableDeclSpec().ClearConstexprSpec();
1885 const char *PrevSpec;
1886 unsigned DiagID;
1887 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1888 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001889 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001890 assert(!Failed && "Making a constexpr member const shouldn't fail");
1891 } else {
1892 B << 1;
1893 const char *PrevSpec;
1894 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001895 if (D.getMutableDeclSpec().SetStorageClassSpec(
1896 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001897 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001898 "This is the only DeclSpec that should fail to be applied");
1899 B << 1;
1900 } else {
1901 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1902 isInstField = false;
1903 }
1904 }
1905 }
1906
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001907 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001908 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001909 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001910
1911 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001912 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001913 Diag(Loc, diag::err_bad_variable_name)
1914 << Name;
1915 return 0;
1916 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001917
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001918 IdentifierInfo *II = Name.getAsIdentifierInfo();
1919
Douglas Gregorf2503652011-09-21 14:40:46 +00001920 // Member field could not be with "template" keyword.
1921 // So TemplateParameterLists should be empty in this case.
1922 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001923 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001924 if (TemplateParams->size()) {
1925 // There is no such thing as a member field template.
1926 Diag(D.getIdentifierLoc(), diag::err_template_member)
1927 << II
1928 << SourceRange(TemplateParams->getTemplateLoc(),
1929 TemplateParams->getRAngleLoc());
1930 } else {
1931 // There is an extraneous 'template<>' for this member.
1932 Diag(TemplateParams->getTemplateLoc(),
1933 diag::err_template_member_noparams)
1934 << II
1935 << SourceRange(TemplateParams->getTemplateLoc(),
1936 TemplateParams->getRAngleLoc());
1937 }
1938 return 0;
1939 }
1940
Douglas Gregor922fff22010-10-13 22:19:53 +00001941 if (SS.isSet() && !SS.isInvalid()) {
1942 // The user provided a superfluous scope specifier inside a class
1943 // definition:
1944 //
1945 // class X {
1946 // int X::member;
1947 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001948 if (DeclContext *DC = computeDeclContext(SS, false))
1949 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001950 else
1951 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1952 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001953
Douglas Gregor922fff22010-10-13 22:19:53 +00001954 SS.clear();
1955 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001956
John McCall76da55d2013-04-16 07:28:30 +00001957 AttributeList *MSPropertyAttr =
1958 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001959 if (MSPropertyAttr) {
1960 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1961 BitWidth, InitStyle, AS, MSPropertyAttr);
1962 if (!Member)
1963 return 0;
1964 isInstField = false;
1965 } else {
1966 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1967 BitWidth, InitStyle, AS);
1968 assert(Member && "HandleField never returns null");
1969 }
1970 } else {
1971 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1972
1973 Member = HandleDeclarator(S, D, TemplateParameterLists);
1974 if (!Member)
1975 return 0;
1976
1977 // Non-instance-fields can't have a bitfield.
1978 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001979 if (Member->isInvalidDecl()) {
1980 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001981 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001982 // C++ 9.6p3: A bit-field shall not be a static member.
1983 // "static member 'A' cannot be a bit-field"
1984 Diag(Loc, diag::err_static_not_bitfield)
1985 << Name << BitWidth->getSourceRange();
1986 } else if (isa<TypedefDecl>(Member)) {
1987 // "typedef member 'x' cannot be a bit-field"
1988 Diag(Loc, diag::err_typedef_not_bitfield)
1989 << Name << BitWidth->getSourceRange();
1990 } else {
1991 // A function typedef ("typedef int f(); f a;").
1992 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1993 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001994 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001995 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001996 }
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Chris Lattner8b963ef2009-03-05 23:01:03 +00001998 BitWidth = 0;
1999 Member->setInvalidDecl();
2000 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002001
2002 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Douglas Gregor37b372b2009-08-20 22:52:58 +00002004 // If we have declared a member function template, set the access of the
2005 // templated declaration as well.
2006 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2007 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002008 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002009
Richard Smitha4b39652012-08-06 03:25:17 +00002010 if (VS.isOverrideSpecified())
2011 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2012 if (VS.isFinalSpecified())
2013 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002014
Douglas Gregorf5251602011-03-08 17:10:18 +00002015 if (VS.getLastLocation().isValid()) {
2016 // Update the end location of a method that has a virt-specifiers.
2017 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2018 MD->setRangeEnd(VS.getLastLocation());
2019 }
Richard Smitha4b39652012-08-06 03:25:17 +00002020
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002021 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002022
Douglas Gregor10bd3682008-11-17 22:58:34 +00002023 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002024
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002025 if (isInstField) {
2026 FieldDecl *FD = cast<FieldDecl>(Member);
2027 FieldCollector->Add(FD);
2028
2029 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2030 FD->getLocation())
2031 != DiagnosticsEngine::Ignored) {
2032 // Remember all explicit private FieldDecls that have a name, no side
2033 // effects and are not part of a dependent type declaration.
2034 if (!FD->isImplicit() && FD->getDeclName() &&
2035 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002036 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002037 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002038 !InitializationHasSideEffects(*FD))
2039 UnusedPrivateFields.insert(FD);
2040 }
2041 }
2042
John McCalld226f652010-08-21 09:40:31 +00002043 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002044}
2045
Hans Wennborg471f9852012-09-18 15:58:06 +00002046namespace {
2047 class UninitializedFieldVisitor
2048 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2049 Sema &S;
2050 ValueDecl *VD;
2051 public:
2052 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2053 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002054 S(S) {
2055 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2056 this->VD = IFD->getAnonField();
2057 else
2058 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002059 }
2060
2061 void HandleExpr(Expr *E) {
2062 if (!E) return;
2063
2064 // Expressions like x(x) sometimes lack the surrounding expressions
2065 // but need to be checked anyways.
2066 HandleValue(E);
2067 Visit(E);
2068 }
2069
2070 void HandleValue(Expr *E) {
2071 E = E->IgnoreParens();
2072
2073 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2074 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002075 return;
2076
2077 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2078 // or union.
2079 MemberExpr *FieldME = ME;
2080
Hans Wennborg471f9852012-09-18 15:58:06 +00002081 Expr *Base = E;
2082 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002083 ME = cast<MemberExpr>(Base);
2084
2085 if (isa<VarDecl>(ME->getMemberDecl()))
2086 return;
2087
2088 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2089 if (!FD->isAnonymousStructOrUnion())
2090 FieldME = ME;
2091
Hans Wennborg471f9852012-09-18 15:58:06 +00002092 Base = ME->getBase();
2093 }
2094
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002095 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002096 unsigned diag = VD->getType()->isReferenceType()
2097 ? diag::warn_reference_field_is_uninit
2098 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002099 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002100 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002101 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002102 }
2103
2104 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2105 HandleValue(CO->getTrueExpr());
2106 HandleValue(CO->getFalseExpr());
2107 return;
2108 }
2109
2110 if (BinaryConditionalOperator *BCO =
2111 dyn_cast<BinaryConditionalOperator>(E)) {
2112 HandleValue(BCO->getCommon());
2113 HandleValue(BCO->getFalseExpr());
2114 return;
2115 }
2116
2117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2118 switch (BO->getOpcode()) {
2119 default:
2120 return;
2121 case(BO_PtrMemD):
2122 case(BO_PtrMemI):
2123 HandleValue(BO->getLHS());
2124 return;
2125 case(BO_Comma):
2126 HandleValue(BO->getRHS());
2127 return;
2128 }
2129 }
2130 }
2131
2132 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2133 if (E->getCastKind() == CK_LValueToRValue)
2134 HandleValue(E->getSubExpr());
2135
2136 Inherited::VisitImplicitCastExpr(E);
2137 }
2138
2139 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2140 Expr *Callee = E->getCallee();
2141 if (isa<MemberExpr>(Callee))
2142 HandleValue(Callee);
2143
2144 Inherited::VisitCXXMemberCallExpr(E);
2145 }
2146 };
2147 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2148 ValueDecl *VD) {
2149 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2150 }
2151} // namespace
2152
Richard Smith7a614d82011-06-11 17:19:42 +00002153/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002154/// in-class initializer for a non-static C++ class member, and after
2155/// instantiating an in-class initializer in a class template. Such actions
2156/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002157void
Richard Smithca523302012-06-10 03:12:00 +00002158Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002159 Expr *InitExpr) {
2160 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002161 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2162 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002163
2164 if (!InitExpr) {
2165 FD->setInvalidDecl();
2166 FD->removeInClassInitializer();
2167 return;
2168 }
2169
Peter Collingbournefef21892011-10-23 18:59:44 +00002170 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2171 FD->setInvalidDecl();
2172 FD->removeInClassInitializer();
2173 return;
2174 }
2175
Hans Wennborg471f9852012-09-18 15:58:06 +00002176 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2177 != DiagnosticsEngine::Ignored) {
2178 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2179 }
2180
Richard Smith7a614d82011-06-11 17:19:42 +00002181 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002182 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002183 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002184 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002185 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002186 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002187 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2188 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002189 if (Init.isInvalid()) {
2190 FD->setInvalidDecl();
2191 return;
2192 }
Richard Smith7a614d82011-06-11 17:19:42 +00002193 }
2194
Richard Smith41956372013-01-14 22:39:08 +00002195 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002196 // The initialization of each base and member constitutes a
2197 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002198 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002199 if (Init.isInvalid()) {
2200 FD->setInvalidDecl();
2201 return;
2202 }
2203
2204 InitExpr = Init.release();
2205
2206 FD->setInClassInitializer(InitExpr);
2207}
2208
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002209/// \brief Find the direct and/or virtual base specifiers that
2210/// correspond to the given base type, for use in base initialization
2211/// within a constructor.
2212static bool FindBaseInitializer(Sema &SemaRef,
2213 CXXRecordDecl *ClassDecl,
2214 QualType BaseType,
2215 const CXXBaseSpecifier *&DirectBaseSpec,
2216 const CXXBaseSpecifier *&VirtualBaseSpec) {
2217 // First, check for a direct base class.
2218 DirectBaseSpec = 0;
2219 for (CXXRecordDecl::base_class_const_iterator Base
2220 = ClassDecl->bases_begin();
2221 Base != ClassDecl->bases_end(); ++Base) {
2222 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2223 // We found a direct base of this type. That's what we're
2224 // initializing.
2225 DirectBaseSpec = &*Base;
2226 break;
2227 }
2228 }
2229
2230 // Check for a virtual base class.
2231 // FIXME: We might be able to short-circuit this if we know in advance that
2232 // there are no virtual bases.
2233 VirtualBaseSpec = 0;
2234 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2235 // We haven't found a base yet; search the class hierarchy for a
2236 // virtual base class.
2237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2238 /*DetectVirtual=*/false);
2239 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2240 BaseType, Paths)) {
2241 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2242 Path != Paths.end(); ++Path) {
2243 if (Path->back().Base->isVirtual()) {
2244 VirtualBaseSpec = Path->back().Base;
2245 break;
2246 }
2247 }
2248 }
2249 }
2250
2251 return DirectBaseSpec || VirtualBaseSpec;
2252}
2253
Sebastian Redl6df65482011-09-24 17:48:25 +00002254/// \brief Handle a C++ member initializer using braced-init-list syntax.
2255MemInitResult
2256Sema::ActOnMemInitializer(Decl *ConstructorD,
2257 Scope *S,
2258 CXXScopeSpec &SS,
2259 IdentifierInfo *MemberOrBase,
2260 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002261 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002262 SourceLocation IdLoc,
2263 Expr *InitList,
2264 SourceLocation EllipsisLoc) {
2265 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002266 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002267 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002268}
2269
2270/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002271MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002272Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002273 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002274 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002275 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002276 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002277 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002278 SourceLocation IdLoc,
2279 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002280 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002281 SourceLocation RParenLoc,
2282 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002283 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002284 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002285 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002286 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002287}
2288
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002289namespace {
2290
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002291// Callback to only accept typo corrections that can be a valid C++ member
2292// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002293class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2294 public:
2295 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2296 : ClassDecl(ClassDecl) {}
2297
2298 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2299 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2300 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2301 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2302 else
2303 return isa<TypeDecl>(ND);
2304 }
2305 return false;
2306 }
2307
2308 private:
2309 CXXRecordDecl *ClassDecl;
2310};
2311
2312}
2313
Sebastian Redl6df65482011-09-24 17:48:25 +00002314/// \brief Handle a C++ member initializer.
2315MemInitResult
2316Sema::BuildMemInitializer(Decl *ConstructorD,
2317 Scope *S,
2318 CXXScopeSpec &SS,
2319 IdentifierInfo *MemberOrBase,
2320 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002321 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002322 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002323 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002324 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002325 if (!ConstructorD)
2326 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002328 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002329
2330 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002331 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002332 if (!Constructor) {
2333 // The user wrote a constructor initializer on a function that is
2334 // not a C++ constructor. Ignore the error for now, because we may
2335 // have more member initializers coming; we'll diagnose it just
2336 // once in ActOnMemInitializers.
2337 return true;
2338 }
2339
2340 CXXRecordDecl *ClassDecl = Constructor->getParent();
2341
2342 // C++ [class.base.init]p2:
2343 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002344 // constructor's class and, if not found in that scope, are looked
2345 // up in the scope containing the constructor's definition.
2346 // [Note: if the constructor's class contains a member with the
2347 // same name as a direct or virtual base class of the class, a
2348 // mem-initializer-id naming the member or base class and composed
2349 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002350 // mem-initializer-id for the hidden base class may be specified
2351 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002352 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002353 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002354 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002355 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002356 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002357 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002358 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2359 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002360 if (EllipsisLoc.isValid())
2361 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002362 << MemberOrBase
2363 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002364
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002365 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002366 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002367 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002368 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002369 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002370 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002371 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002372
2373 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002374 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002375 } else if (DS.getTypeSpecType() == TST_decltype) {
2376 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002377 } else {
2378 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2379 LookupParsedName(R, S, &SS);
2380
2381 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2382 if (!TyD) {
2383 if (R.isAmbiguous()) return true;
2384
John McCallfd225442010-04-09 19:01:14 +00002385 // We don't want access-control diagnostics here.
2386 R.suppressDiagnostics();
2387
Douglas Gregor7a886e12010-01-19 06:46:48 +00002388 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2389 bool NotUnknownSpecialization = false;
2390 DeclContext *DC = computeDeclContext(SS, false);
2391 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2392 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2393
2394 if (!NotUnknownSpecialization) {
2395 // When the scope specifier can refer to a member of an unknown
2396 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002397 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2398 SS.getWithLocInContext(Context),
2399 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002400 if (BaseType.isNull())
2401 return true;
2402
Douglas Gregor7a886e12010-01-19 06:46:48 +00002403 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002404 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002405 }
2406 }
2407
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002408 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002409 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002410 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002411 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002412 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002413 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002414 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2415 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002416 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002417 // We have found a non-static data member with a similar
2418 // name to what was typed; complain and initialize that
2419 // member.
2420 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2421 << MemberOrBase << true << CorrectedQuotedStr
2422 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2423 Diag(Member->getLocation(), diag::note_previous_decl)
2424 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002425
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002426 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002427 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002428 const CXXBaseSpecifier *DirectBaseSpec;
2429 const CXXBaseSpecifier *VirtualBaseSpec;
2430 if (FindBaseInitializer(*this, ClassDecl,
2431 Context.getTypeDeclType(Type),
2432 DirectBaseSpec, VirtualBaseSpec)) {
2433 // We have found a direct or virtual base class with a
2434 // similar name to what was typed; complain and initialize
2435 // that base class.
2436 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002437 << MemberOrBase << false << CorrectedQuotedStr
2438 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002439
2440 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2441 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002442 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002443 diag::note_base_class_specified_here)
2444 << BaseSpec->getType()
2445 << BaseSpec->getSourceRange();
2446
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002447 TyD = Type;
2448 }
2449 }
2450 }
2451
Douglas Gregor7a886e12010-01-19 06:46:48 +00002452 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002453 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002454 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002455 return true;
2456 }
John McCall2b194412009-12-21 10:41:20 +00002457 }
2458
Douglas Gregor7a886e12010-01-19 06:46:48 +00002459 if (BaseType.isNull()) {
2460 BaseType = Context.getTypeDeclType(TyD);
2461 if (SS.isSet()) {
2462 NestedNameSpecifier *Qualifier =
2463 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002464
Douglas Gregor7a886e12010-01-19 06:46:48 +00002465 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002466 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002467 }
John McCall2b194412009-12-21 10:41:20 +00002468 }
2469 }
Mike Stump1eb44332009-09-09 15:08:12 +00002470
John McCalla93c9342009-12-07 02:54:59 +00002471 if (!TInfo)
2472 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002473
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002474 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002475}
2476
Chandler Carruth81c64772011-09-03 01:14:15 +00002477/// Checks a member initializer expression for cases where reference (or
2478/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002479static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2480 Expr *Init,
2481 SourceLocation IdLoc) {
2482 QualType MemberTy = Member->getType();
2483
2484 // We only handle pointers and references currently.
2485 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2486 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2487 return;
2488
2489 const bool IsPointer = MemberTy->isPointerType();
2490 if (IsPointer) {
2491 if (const UnaryOperator *Op
2492 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2493 // The only case we're worried about with pointers requires taking the
2494 // address.
2495 if (Op->getOpcode() != UO_AddrOf)
2496 return;
2497
2498 Init = Op->getSubExpr();
2499 } else {
2500 // We only handle address-of expression initializers for pointers.
2501 return;
2502 }
2503 }
2504
Richard Smitha4bb99c2013-06-12 21:51:50 +00002505 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002506 // We only warn when referring to a non-reference parameter declaration.
2507 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2508 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002509 return;
2510
2511 S.Diag(Init->getExprLoc(),
2512 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2513 : diag::warn_bind_ref_member_to_parameter)
2514 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002515 } else {
2516 // Other initializers are fine.
2517 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002518 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002519
2520 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2521 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002522}
2523
John McCallf312b1e2010-08-26 23:41:50 +00002524MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002526 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002527 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2528 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2529 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002530 "Member must be a FieldDecl or IndirectFieldDecl");
2531
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002532 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002533 return true;
2534
Douglas Gregor464b2f02010-11-05 22:21:31 +00002535 if (Member->isInvalidDecl())
2536 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002537
John McCallb4190042009-11-04 23:02:40 +00002538 // Diagnose value-uses of fields to initialize themselves, e.g.
2539 // foo(foo)
2540 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002541 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002542 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002544 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002545 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002546 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002547 } else {
2548 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002549 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002550 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002551
Richard Trieude5e75c2012-06-14 23:11:34 +00002552 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2553 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002554 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002555 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002556 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002557 // initializing the i'th field, throw a warning if any of the >= i'th
2558 // fields are used, as they are not yet initialized.
2559 // Right now we are only handling the case where the i'th field uses
2560 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002561 // Also need to take into account that some fields may be initialized by
2562 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002563 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002564
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002565 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002566
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002567 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002568 // Can't check initialization for a member of dependent type or when
2569 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002570 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002571 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002572 bool InitList = false;
2573 if (isa<InitListExpr>(Init)) {
2574 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002575 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002576 }
2577
Chandler Carruth894aed92010-12-06 09:23:57 +00002578 // Initialize the member.
2579 InitializedEntity MemberEntity =
2580 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2581 : InitializedEntity::InitializeMember(IndirectMember, 0);
2582 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002583 InitList ? InitializationKind::CreateDirectList(IdLoc)
2584 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2585 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002586
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002587 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2588 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002589 if (MemberInit.isInvalid())
2590 return true;
2591
Richard Smith8a07cd32013-06-12 20:42:33 +00002592 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2593
Richard Smith41956372013-01-14 22:39:08 +00002594 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002595 // The initialization of each base and member constitutes a
2596 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002597 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002598 if (MemberInit.isInvalid())
2599 return true;
2600
Richard Smithc83c2302012-12-19 01:39:02 +00002601 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002602 }
2603
Chandler Carruth894aed92010-12-06 09:23:57 +00002604 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002605 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2606 InitRange.getBegin(), Init,
2607 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002608 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002609 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2610 InitRange.getBegin(), Init,
2611 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002612 }
Eli Friedman59c04372009-07-29 19:44:27 +00002613}
2614
John McCallf312b1e2010-08-26 23:41:50 +00002615MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002616Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002617 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002618 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002619 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002620 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002621 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002622 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002623
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002624 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002625 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002626 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2627 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002628 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002629 }
2630
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002631 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002632 // Initialize the object.
2633 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2634 QualType(ClassDecl->getTypeForDecl(), 0));
2635 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002636 InitList ? InitializationKind::CreateDirectList(NameLoc)
2637 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2638 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002639 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002640 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002641 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002642 if (DelegationInit.isInvalid())
2643 return true;
2644
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002645 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2646 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002647
Richard Smith41956372013-01-14 22:39:08 +00002648 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002649 // The initialization of each base and member constitutes a
2650 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002651 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2652 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002653 if (DelegationInit.isInvalid())
2654 return true;
2655
Eli Friedmand21016f2012-05-19 23:35:23 +00002656 // If we are in a dependent context, template instantiation will
2657 // perform this type-checking again. Just save the arguments that we
2658 // received in a ParenListExpr.
2659 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2660 // of the information that we have about the base
2661 // initializer. However, deconstructing the ASTs is a dicey process,
2662 // and this approach is far more likely to get the corner cases right.
2663 if (CurContext->isDependentContext())
2664 DelegationInit = Owned(Init);
2665
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002666 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002667 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002668 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002669}
2670
2671MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002672Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002673 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002674 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002675 SourceLocation BaseLoc
2676 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002677
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002678 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2679 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2680 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2681
2682 // C++ [class.base.init]p2:
2683 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002684 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002685 // of that class, the mem-initializer is ill-formed. A
2686 // mem-initializer-list can initialize a base class using any
2687 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002688 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002689
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002690 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002691 if (EllipsisLoc.isValid()) {
2692 // This is a pack expansion.
2693 if (!BaseType->containsUnexpandedParameterPack()) {
2694 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002695 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002696
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002697 EllipsisLoc = SourceLocation();
2698 }
2699 } else {
2700 // Check for any unexpanded parameter packs.
2701 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2702 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002703
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002704 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002705 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002706 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002707
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002708 // Check for direct and virtual base classes.
2709 const CXXBaseSpecifier *DirectBaseSpec = 0;
2710 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2711 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002712 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2713 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002714 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002715
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002716 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2717 VirtualBaseSpec);
2718
2719 // C++ [base.class.init]p2:
2720 // Unless the mem-initializer-id names a nonstatic data member of the
2721 // constructor's class or a direct or virtual base of that class, the
2722 // mem-initializer is ill-formed.
2723 if (!DirectBaseSpec && !VirtualBaseSpec) {
2724 // If the class has any dependent bases, then it's possible that
2725 // one of those types will resolve to the same type as
2726 // BaseType. Therefore, just treat this as a dependent base
2727 // class initialization. FIXME: Should we try to check the
2728 // initialization anyway? It seems odd.
2729 if (ClassDecl->hasAnyDependentBases())
2730 Dependent = true;
2731 else
2732 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2733 << BaseType << Context.getTypeDeclType(ClassDecl)
2734 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2735 }
2736 }
2737
2738 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002739 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Sebastian Redl6df65482011-09-24 17:48:25 +00002741 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2742 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002743 InitRange.getBegin(), Init,
2744 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002745 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002746
2747 // C++ [base.class.init]p2:
2748 // If a mem-initializer-id is ambiguous because it designates both
2749 // a direct non-virtual base class and an inherited virtual base
2750 // class, the mem-initializer is ill-formed.
2751 if (DirectBaseSpec && VirtualBaseSpec)
2752 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002753 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002754
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002755 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002756 if (!BaseSpec)
2757 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2758
2759 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002760 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002761 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002762 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002763 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002764 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002765 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002766
2767 InitializedEntity BaseEntity =
2768 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2769 InitializationKind Kind =
2770 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2771 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2772 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002773 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2774 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002775 if (BaseInit.isInvalid())
2776 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002777
Richard Smith41956372013-01-14 22:39:08 +00002778 // C++11 [class.base.init]p7:
2779 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002780 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002781 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002782 if (BaseInit.isInvalid())
2783 return true;
2784
2785 // If we are in a dependent context, template instantiation will
2786 // perform this type-checking again. Just save the arguments that we
2787 // received in a ParenListExpr.
2788 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2789 // of the information that we have about the base
2790 // initializer. However, deconstructing the ASTs is a dicey process,
2791 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002792 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002793 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002794
Sean Huntcbb67482011-01-08 20:30:50 +00002795 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002796 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002797 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002798 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002799 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002800}
2801
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002802// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002803static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2804 if (T.isNull()) T = E->getType();
2805 QualType TargetType = SemaRef.BuildReferenceType(
2806 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002807 SourceLocation ExprLoc = E->getLocStart();
2808 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2809 TargetType, ExprLoc);
2810
2811 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2812 SourceRange(ExprLoc, ExprLoc),
2813 E->getSourceRange()).take();
2814}
2815
Anders Carlssone5ef7402010-04-23 03:10:23 +00002816/// ImplicitInitializerKind - How an implicit base or member initializer should
2817/// initialize its base or member.
2818enum ImplicitInitializerKind {
2819 IIK_Default,
2820 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002821 IIK_Move,
2822 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002823};
2824
Anders Carlssondefefd22010-04-23 02:00:02 +00002825static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002826BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002827 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002828 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002829 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002830 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002831 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002832 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2833 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002834
John McCall60d7b3a2010-08-24 06:29:42 +00002835 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002836
2837 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002838 case IIK_Inherit: {
2839 const CXXRecordDecl *Inherited =
2840 Constructor->getInheritedConstructor()->getParent();
2841 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2842 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2843 // C++11 [class.inhctor]p8:
2844 // Each expression in the expression-list is of the form
2845 // static_cast<T&&>(p), where p is the name of the corresponding
2846 // constructor parameter and T is the declared type of p.
2847 SmallVector<Expr*, 16> Args;
2848 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2849 ParmVarDecl *PD = Constructor->getParamDecl(I);
2850 ExprResult ArgExpr =
2851 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2852 VK_LValue, SourceLocation());
2853 if (ArgExpr.isInvalid())
2854 return true;
2855 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2856 }
2857
2858 InitializationKind InitKind = InitializationKind::CreateDirect(
2859 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002860 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002861 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2862 break;
2863 }
2864 }
2865 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002866 case IIK_Default: {
2867 InitializationKind InitKind
2868 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002869 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2870 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002871 break;
2872 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002873
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002874 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002875 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002876 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002877 ParmVarDecl *Param = Constructor->getParamDecl(0);
2878 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002879
Anders Carlssone5ef7402010-04-23 03:10:23 +00002880 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002881 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002882 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002883 Constructor->getLocation(), ParamType,
2884 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002885
Eli Friedman5f2987c2012-02-02 03:46:19 +00002886 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2887
Anders Carlssonc7957502010-04-24 22:02:54 +00002888 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002889 QualType ArgTy =
2890 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2891 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002892
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002893 if (Moving) {
2894 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2895 }
2896
John McCallf871d0c2010-08-07 06:22:56 +00002897 CXXCastPath BasePath;
2898 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002899 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2900 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002901 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002902 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002903
Anders Carlssone5ef7402010-04-23 03:10:23 +00002904 InitializationKind InitKind
2905 = InitializationKind::CreateDirect(Constructor->getLocation(),
2906 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002907 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2908 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002909 break;
2910 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002911 }
John McCall9ae2f072010-08-23 23:25:46 +00002912
Douglas Gregor53c374f2010-12-07 00:41:46 +00002913 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002914 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002915 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002916
Anders Carlssondefefd22010-04-23 02:00:02 +00002917 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002918 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002919 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2920 SourceLocation()),
2921 BaseSpec->isVirtual(),
2922 SourceLocation(),
2923 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002924 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002925 SourceLocation());
2926
Anders Carlssondefefd22010-04-23 02:00:02 +00002927 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002928}
2929
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002930static bool RefersToRValueRef(Expr *MemRef) {
2931 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2932 return Referenced->getType()->isRValueReferenceType();
2933}
2934
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002935static bool
2936BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002937 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002938 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002939 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002940 if (Field->isInvalidDecl())
2941 return true;
2942
Chandler Carruthf186b542010-06-29 23:50:44 +00002943 SourceLocation Loc = Constructor->getLocation();
2944
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002945 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2946 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002947 ParmVarDecl *Param = Constructor->getParamDecl(0);
2948 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002949
2950 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002951 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2952 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002953
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002954 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002955 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002956 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002957 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002958
Eli Friedman5f2987c2012-02-02 03:46:19 +00002959 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2960
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002961 if (Moving) {
2962 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2963 }
2964
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002965 // Build a reference to this field within the parameter.
2966 CXXScopeSpec SS;
2967 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2968 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002969 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2970 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002971 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002972 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002973 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002974 ParamType, Loc,
2975 /*IsArrow=*/false,
2976 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002977 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002978 /*FirstQualifierInScope=*/0,
2979 MemberLookup,
2980 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002981 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002982 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002983
2984 // C++11 [class.copy]p15:
2985 // - if a member m has rvalue reference type T&&, it is direct-initialized
2986 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002987 if (RefersToRValueRef(CtorArg.get())) {
2988 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002989 }
2990
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002991 // When the field we are copying is an array, create index variables for
2992 // each dimension of the array. We use these index variables to subscript
2993 // the source array, and other clients (e.g., CodeGen) will perform the
2994 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002995 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002996 QualType BaseType = Field->getType();
2997 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002998 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002999 while (const ConstantArrayType *Array
3000 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003001 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003002 // Create the iteration variable for this array index.
3003 IdentifierInfo *IterationVarName = 0;
3004 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003005 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003006 llvm::raw_svector_ostream OS(Str);
3007 OS << "__i" << IndexVariables.size();
3008 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3009 }
3010 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003011 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003012 IterationVarName, SizeType,
3013 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003014 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003015 IndexVariables.push_back(IterationVar);
3016
3017 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003018 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003019 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003020 assert(!IterationVarRef.isInvalid() &&
3021 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003022 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3023 assert(!IterationVarRef.isInvalid() &&
3024 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003025
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003026 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003027 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003028 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003029 Loc);
3030 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003031 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003032
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003033 BaseType = Array->getElementType();
3034 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003035
3036 // The array subscript expression is an lvalue, which is wrong for moving.
3037 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003038 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003039
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003040 // Construct the entity that we will be initializing. For an array, this
3041 // will be first element in the array, which may require several levels
3042 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003043 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003044 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003045 if (Indirect)
3046 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3047 else
3048 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003049 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3050 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3051 0,
3052 Entities.back()));
3053
3054 // Direct-initialize to use the copy constructor.
3055 InitializationKind InitKind =
3056 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3057
Sebastian Redl74e611a2011-09-04 18:14:28 +00003058 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003059 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003060
John McCall60d7b3a2010-08-24 06:29:42 +00003061 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003062 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003063 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003064 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003065 if (MemberInit.isInvalid())
3066 return true;
3067
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003068 if (Indirect) {
3069 assert(IndexVariables.size() == 0 &&
3070 "Indirect field improperly initialized");
3071 CXXMemberInit
3072 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3073 Loc, Loc,
3074 MemberInit.takeAs<Expr>(),
3075 Loc);
3076 } else
3077 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3078 Loc, MemberInit.takeAs<Expr>(),
3079 Loc,
3080 IndexVariables.data(),
3081 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003082 return false;
3083 }
3084
Richard Smith07b0fdc2013-03-18 21:12:30 +00003085 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3086 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003087
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003088 QualType FieldBaseElementType =
3089 SemaRef.Context.getBaseElementType(Field->getType());
3090
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003091 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003092 InitializedEntity InitEntity
3093 = Indirect? InitializedEntity::InitializeMember(Indirect)
3094 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003095 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003096 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003097
3098 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3099 ExprResult MemberInit =
3100 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003101
Douglas Gregor53c374f2010-12-07 00:41:46 +00003102 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003103 if (MemberInit.isInvalid())
3104 return true;
3105
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003106 if (Indirect)
3107 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3108 Indirect, Loc,
3109 Loc,
3110 MemberInit.get(),
3111 Loc);
3112 else
3113 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3114 Field, Loc, Loc,
3115 MemberInit.get(),
3116 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003117 return false;
3118 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003119
Sean Hunt1f2f3842011-05-17 00:19:05 +00003120 if (!Field->getParent()->isUnion()) {
3121 if (FieldBaseElementType->isReferenceType()) {
3122 SemaRef.Diag(Constructor->getLocation(),
3123 diag::err_uninitialized_member_in_ctor)
3124 << (int)Constructor->isImplicit()
3125 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3126 << 0 << Field->getDeclName();
3127 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3128 return true;
3129 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003130
Sean Hunt1f2f3842011-05-17 00:19:05 +00003131 if (FieldBaseElementType.isConstQualified()) {
3132 SemaRef.Diag(Constructor->getLocation(),
3133 diag::err_uninitialized_member_in_ctor)
3134 << (int)Constructor->isImplicit()
3135 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3136 << 1 << Field->getDeclName();
3137 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3138 return true;
3139 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003140 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003141
David Blaikie4e4d0842012-03-11 07:00:24 +00003142 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003143 FieldBaseElementType->isObjCRetainableType() &&
3144 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3145 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003146 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003147 // Default-initialize Objective-C pointers to NULL.
3148 CXXMemberInit
3149 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3150 Loc, Loc,
3151 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3152 Loc);
3153 return false;
3154 }
3155
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003156 // Nothing to initialize.
3157 CXXMemberInit = 0;
3158 return false;
3159}
John McCallf1860e52010-05-20 23:23:51 +00003160
3161namespace {
3162struct BaseAndFieldInfo {
3163 Sema &S;
3164 CXXConstructorDecl *Ctor;
3165 bool AnyErrorsInInits;
3166 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003167 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003168 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003169
3170 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3171 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003172 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3173 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003174 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003175 else if (Generated && Ctor->isMoveConstructor())
3176 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003177 else if (Ctor->getInheritedConstructor())
3178 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003179 else
3180 IIK = IIK_Default;
3181 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003182
3183 bool isImplicitCopyOrMove() const {
3184 switch (IIK) {
3185 case IIK_Copy:
3186 case IIK_Move:
3187 return true;
3188
3189 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003190 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003191 return false;
3192 }
David Blaikie30263482012-01-20 21:50:17 +00003193
3194 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003195 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003196
3197 bool addFieldInitializer(CXXCtorInitializer *Init) {
3198 AllToInit.push_back(Init);
3199
3200 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003201 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003202 S.UnusedPrivateFields.remove(Init->getAnyMember());
3203
3204 return false;
3205 }
John McCallf1860e52010-05-20 23:23:51 +00003206};
3207}
3208
Richard Smitha4950662011-09-19 13:34:43 +00003209/// \brief Determine whether the given indirect field declaration is somewhere
3210/// within an anonymous union.
3211static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3212 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3213 CEnd = F->chain_end();
3214 C != CEnd; ++C)
3215 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3216 if (Record->isUnion())
3217 return true;
3218
3219 return false;
3220}
3221
Douglas Gregorddb21472011-11-02 23:04:16 +00003222/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3223/// array type.
3224static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3225 if (T->isIncompleteArrayType())
3226 return true;
3227
3228 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3229 if (!ArrayT->getSize())
3230 return true;
3231
3232 T = ArrayT->getElementType();
3233 }
3234
3235 return false;
3236}
3237
Richard Smith7a614d82011-06-11 17:19:42 +00003238static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003239 FieldDecl *Field,
3240 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003241 if (Field->isInvalidDecl())
3242 return false;
John McCallf1860e52010-05-20 23:23:51 +00003243
Chandler Carruthe861c602010-06-30 02:59:29 +00003244 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003245 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3246 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003247
Richard Smith0b8220a2012-08-07 21:30:42 +00003248 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003249 // has a brace-or-equal-initializer, the entity is initialized as specified
3250 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003251 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003252 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3253 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003254 CXXCtorInitializer *Init;
3255 if (Indirect)
3256 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3257 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003258 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003259 SourceLocation());
3260 else
3261 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3262 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003263 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003264 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003265 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003266 }
3267
Richard Smithc115f632011-09-18 11:14:50 +00003268 // Don't build an implicit initializer for union members if none was
3269 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003270 if (Field->getParent()->isUnion() ||
3271 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003272 return false;
3273
Douglas Gregorddb21472011-11-02 23:04:16 +00003274 // Don't initialize incomplete or zero-length arrays.
3275 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3276 return false;
3277
John McCallf1860e52010-05-20 23:23:51 +00003278 // Don't try to build an implicit initializer if there were semantic
3279 // errors in any of the initializers (and therefore we might be
3280 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003281 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003282 return false;
3283
Sean Huntcbb67482011-01-08 20:30:50 +00003284 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003285 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3286 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003287 return true;
John McCallf1860e52010-05-20 23:23:51 +00003288
Richard Smith0b8220a2012-08-07 21:30:42 +00003289 if (!Init)
3290 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003291
Richard Smith0b8220a2012-08-07 21:30:42 +00003292 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003293}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003294
3295bool
3296Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3297 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003298 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003299 Constructor->setNumCtorInitializers(1);
3300 CXXCtorInitializer **initializer =
3301 new (Context) CXXCtorInitializer*[1];
3302 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3303 Constructor->setCtorInitializers(initializer);
3304
Sean Huntb76af9c2011-05-03 23:05:34 +00003305 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003306 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003307 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3308 }
3309
Sean Huntc1598702011-05-05 00:05:47 +00003310 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003311
Sean Hunt059ce0d2011-05-01 07:04:31 +00003312 return false;
3313}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003314
David Blaikie93c86172013-01-17 05:26:25 +00003315bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3316 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003317 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003318 // Just store the initializers as written, they will be checked during
3319 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003320 if (!Initializers.empty()) {
3321 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003322 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003323 new (Context) CXXCtorInitializer*[Initializers.size()];
3324 memcpy(baseOrMemberInitializers, Initializers.data(),
3325 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003326 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003327 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003328
3329 // Let template instantiation know whether we had errors.
3330 if (AnyErrors)
3331 Constructor->setInvalidDecl();
3332
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003333 return false;
3334 }
3335
John McCallf1860e52010-05-20 23:23:51 +00003336 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003337
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003338 // We need to build the initializer AST according to order of construction
3339 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003340 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003341 if (!ClassDecl)
3342 return true;
3343
Eli Friedman80c30da2009-11-09 19:20:36 +00003344 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003345
David Blaikie93c86172013-01-17 05:26:25 +00003346 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003347 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003348
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003349 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003350 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003351 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003352 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003353 }
3354
Anders Carlsson711f34a2010-04-21 19:52:01 +00003355 // Keep track of the direct virtual bases.
3356 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3357 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3358 E = ClassDecl->bases_end(); I != E; ++I) {
3359 if (I->isVirtual())
3360 DirectVBases.insert(I);
3361 }
3362
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003363 // Push virtual bases before others.
3364 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3365 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3366
Sean Huntcbb67482011-01-08 20:30:50 +00003367 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003368 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003369 // [class.base.init]p7, per DR257:
3370 // A mem-initializer where the mem-initializer-id names a virtual base
3371 // class is ignored during execution of a constructor of any class that
3372 // is not the most derived class.
3373 if (ClassDecl->isAbstract()) {
3374 // FIXME: Provide a fixit to remove the base specifier. This requires
3375 // tracking the location of the associated comma for a base specifier.
3376 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3377 << VBase->getType() << ClassDecl;
3378 DiagnoseAbstractType(ClassDecl);
3379 }
3380
John McCallf1860e52010-05-20 23:23:51 +00003381 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003382 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3383 // [class.base.init]p8, per DR257:
3384 // If a given [...] base class is not named by a mem-initializer-id
3385 // [...] and the entity is not a virtual base class of an abstract
3386 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003387 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003388 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003389 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003390 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003391 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003392 HadError = true;
3393 continue;
3394 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003395
John McCallf1860e52010-05-20 23:23:51 +00003396 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003397 }
3398 }
Mike Stump1eb44332009-09-09 15:08:12 +00003399
John McCallf1860e52010-05-20 23:23:51 +00003400 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003401 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3402 E = ClassDecl->bases_end(); Base != E; ++Base) {
3403 // Virtuals are in the virtual base list and already constructed.
3404 if (Base->isVirtual())
3405 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003406
Sean Huntcbb67482011-01-08 20:30:50 +00003407 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003408 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3409 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003410 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003411 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003412 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003413 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003414 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003415 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003416 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003417 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003418
John McCallf1860e52010-05-20 23:23:51 +00003419 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003420 }
3421 }
Mike Stump1eb44332009-09-09 15:08:12 +00003422
John McCallf1860e52010-05-20 23:23:51 +00003423 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003424 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3425 MemEnd = ClassDecl->decls_end();
3426 Mem != MemEnd; ++Mem) {
3427 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003428 // C++ [class.bit]p2:
3429 // A declaration for a bit-field that omits the identifier declares an
3430 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3431 // initialized.
3432 if (F->isUnnamedBitfield())
3433 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003434
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003435 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003436 // handle anonymous struct/union fields based on their individual
3437 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003438 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003439 continue;
3440
3441 if (CollectFieldInitializer(*this, Info, F))
3442 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003443 continue;
3444 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003445
3446 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003447 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003448 continue;
3449
3450 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3451 if (F->getType()->isIncompleteArrayType()) {
3452 assert(ClassDecl->hasFlexibleArrayMember() &&
3453 "Incomplete array type is not valid");
3454 continue;
3455 }
3456
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003457 // Initialize each field of an anonymous struct individually.
3458 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3459 HadError = true;
3460
3461 continue;
3462 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003463 }
Mike Stump1eb44332009-09-09 15:08:12 +00003464
David Blaikie93c86172013-01-17 05:26:25 +00003465 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003466 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003467 Constructor->setNumCtorInitializers(NumInitializers);
3468 CXXCtorInitializer **baseOrMemberInitializers =
3469 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003470 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003471 NumInitializers * sizeof(CXXCtorInitializer*));
3472 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003473
John McCallef027fe2010-03-16 21:39:52 +00003474 // Constructors implicitly reference the base and member
3475 // destructors.
3476 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3477 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003478 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003479
3480 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003481}
3482
David Blaikieee000bb2013-01-17 08:49:22 +00003483static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003484 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003485 const RecordDecl *RD = RT->getDecl();
3486 if (RD->isAnonymousStructOrUnion()) {
3487 for (RecordDecl::field_iterator Field = RD->field_begin(),
3488 E = RD->field_end(); Field != E; ++Field)
3489 PopulateKeysForFields(*Field, IdealInits);
3490 return;
3491 }
Eli Friedman6347f422009-07-21 19:28:10 +00003492 }
David Blaikieee000bb2013-01-17 08:49:22 +00003493 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003494}
3495
Anders Carlssonea356fb2010-04-02 05:42:15 +00003496static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003497 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003498}
3499
Anders Carlssonea356fb2010-04-02 05:42:15 +00003500static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003501 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003502 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003503 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003504
David Blaikieee000bb2013-01-17 08:49:22 +00003505 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003506}
3507
David Blaikie93c86172013-01-17 05:26:25 +00003508static void DiagnoseBaseOrMemInitializerOrder(
3509 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3510 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003511 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003512 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003514 // Don't check initializers order unless the warning is enabled at the
3515 // location of at least one initializer.
3516 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003517 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003518 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003519 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3520 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003521 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003522 ShouldCheckOrder = true;
3523 break;
3524 }
3525 }
3526 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003527 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003528
John McCalld6ca8da2010-04-10 07:37:23 +00003529 // Build the list of bases and members in the order that they'll
3530 // actually be initialized. The explicit initializers should be in
3531 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003532 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Anders Carlsson071d6102010-04-02 03:38:04 +00003534 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3535
John McCalld6ca8da2010-04-10 07:37:23 +00003536 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003537 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003538 ClassDecl->vbases_begin(),
3539 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003540 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003541
John McCalld6ca8da2010-04-10 07:37:23 +00003542 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003543 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003544 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003545 if (Base->isVirtual())
3546 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003547 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003548 }
Mike Stump1eb44332009-09-09 15:08:12 +00003549
John McCalld6ca8da2010-04-10 07:37:23 +00003550 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003551 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003552 E = ClassDecl->field_end(); Field != E; ++Field) {
3553 if (Field->isUnnamedBitfield())
3554 continue;
3555
David Blaikieee000bb2013-01-17 08:49:22 +00003556 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003557 }
3558
John McCalld6ca8da2010-04-10 07:37:23 +00003559 unsigned NumIdealInits = IdealInitKeys.size();
3560 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003561
Sean Huntcbb67482011-01-08 20:30:50 +00003562 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003563 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003564 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003565 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003566
3567 // Scan forward to try to find this initializer in the idealized
3568 // initializers list.
3569 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3570 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003571 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003572
3573 // If we didn't find this initializer, it must be because we
3574 // scanned past it on a previous iteration. That can only
3575 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003576 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003577 Sema::SemaDiagnosticBuilder D =
3578 SemaRef.Diag(PrevInit->getSourceLocation(),
3579 diag::warn_initializer_out_of_order);
3580
Francois Pichet00eb3f92010-12-04 09:14:42 +00003581 if (PrevInit->isAnyMemberInitializer())
3582 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003583 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003584 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003585
Francois Pichet00eb3f92010-12-04 09:14:42 +00003586 if (Init->isAnyMemberInitializer())
3587 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003588 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003589 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003590
3591 // Move back to the initializer's location in the ideal list.
3592 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3593 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003594 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003595
3596 assert(IdealIndex != NumIdealInits &&
3597 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003598 }
John McCalld6ca8da2010-04-10 07:37:23 +00003599
3600 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003601 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003602}
3603
John McCall3c3ccdb2010-04-10 09:28:51 +00003604namespace {
3605bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003606 CXXCtorInitializer *Init,
3607 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003608 if (!PrevInit) {
3609 PrevInit = Init;
3610 return false;
3611 }
3612
Douglas Gregordc392c12013-03-25 23:28:23 +00003613 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003614 S.Diag(Init->getSourceLocation(),
3615 diag::err_multiple_mem_initialization)
3616 << Field->getDeclName()
3617 << Init->getSourceRange();
3618 else {
John McCallf4c73712011-01-19 06:33:43 +00003619 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003620 assert(BaseClass && "neither field nor base");
3621 S.Diag(Init->getSourceLocation(),
3622 diag::err_multiple_base_initialization)
3623 << QualType(BaseClass, 0)
3624 << Init->getSourceRange();
3625 }
3626 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3627 << 0 << PrevInit->getSourceRange();
3628
3629 return true;
3630}
3631
Sean Huntcbb67482011-01-08 20:30:50 +00003632typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003633typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3634
3635bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003636 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003637 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003638 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003639 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003640 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003641
3642 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003643 if (Parent->isUnion()) {
3644 UnionEntry &En = Unions[Parent];
3645 if (En.first && En.first != Child) {
3646 S.Diag(Init->getSourceLocation(),
3647 diag::err_multiple_mem_union_initialization)
3648 << Field->getDeclName()
3649 << Init->getSourceRange();
3650 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3651 << 0 << En.second->getSourceRange();
3652 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003653 }
3654 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003655 En.first = Child;
3656 En.second = Init;
3657 }
David Blaikie6fe29652011-11-17 06:01:57 +00003658 if (!Parent->isAnonymousStructOrUnion())
3659 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003660 }
3661
3662 Child = Parent;
3663 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003664 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003665
3666 return false;
3667}
3668}
3669
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003670/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003671void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003672 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003673 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003674 bool AnyErrors) {
3675 if (!ConstructorDecl)
3676 return;
3677
3678 AdjustDeclIfTemplate(ConstructorDecl);
3679
3680 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003681 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003682
3683 if (!Constructor) {
3684 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3685 return;
3686 }
3687
John McCall3c3ccdb2010-04-10 09:28:51 +00003688 // Mapping for the duplicate initializers check.
3689 // For member initializers, this is keyed with a FieldDecl*.
3690 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003691 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003692
3693 // Mapping for the inconsistent anonymous-union initializers check.
3694 RedundantUnionMap MemberUnions;
3695
Anders Carlssonea356fb2010-04-02 05:42:15 +00003696 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003697 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003698 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003699
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003700 // Set the source order index.
3701 Init->setSourceOrder(i);
3702
Francois Pichet00eb3f92010-12-04 09:14:42 +00003703 if (Init->isAnyMemberInitializer()) {
3704 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003705 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3706 CheckRedundantUnionInit(*this, Init, MemberUnions))
3707 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003708 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003709 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3710 if (CheckRedundantInit(*this, Init, Members[Key]))
3711 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003712 } else {
3713 assert(Init->isDelegatingInitializer());
3714 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003715 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003716 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003717 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003718 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003719 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003720 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003721 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003722 // Return immediately as the initializer is set.
3723 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003724 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003725 }
3726
Anders Carlssonea356fb2010-04-02 05:42:15 +00003727 if (HadError)
3728 return;
3729
David Blaikie93c86172013-01-17 05:26:25 +00003730 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003731
David Blaikie93c86172013-01-17 05:26:25 +00003732 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003733}
3734
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003735void
John McCallef027fe2010-03-16 21:39:52 +00003736Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3737 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003738 // Ignore dependent contexts. Also ignore unions, since their members never
3739 // have destructors implicitly called.
3740 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003741 return;
John McCall58e6f342010-03-16 05:22:47 +00003742
3743 // FIXME: all the access-control diagnostics are positioned on the
3744 // field/base declaration. That's probably good; that said, the
3745 // user might reasonably want to know why the destructor is being
3746 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003747
Anders Carlsson9f853df2009-11-17 04:44:12 +00003748 // Non-static data members.
3749 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3750 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003751 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003752 if (Field->isInvalidDecl())
3753 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003754
3755 // Don't destroy incomplete or zero-length arrays.
3756 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3757 continue;
3758
Anders Carlsson9f853df2009-11-17 04:44:12 +00003759 QualType FieldType = Context.getBaseElementType(Field->getType());
3760
3761 const RecordType* RT = FieldType->getAs<RecordType>();
3762 if (!RT)
3763 continue;
3764
3765 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003766 if (FieldClassDecl->isInvalidDecl())
3767 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003768 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003769 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003770 // The destructor for an implicit anonymous union member is never invoked.
3771 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3772 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003773
Douglas Gregordb89f282010-07-01 22:47:18 +00003774 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003775 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003776 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003777 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003778 << Field->getDeclName()
3779 << FieldType);
3780
Eli Friedman5f2987c2012-02-02 03:46:19 +00003781 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003782 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003783 }
3784
John McCall58e6f342010-03-16 05:22:47 +00003785 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3786
Anders Carlsson9f853df2009-11-17 04:44:12 +00003787 // Bases.
3788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3789 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003790 // Bases are always records in a well-formed non-dependent class.
3791 const RecordType *RT = Base->getType()->getAs<RecordType>();
3792
3793 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003794 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003795 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003796
John McCall58e6f342010-03-16 05:22:47 +00003797 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003798 // If our base class is invalid, we probably can't get its dtor anyway.
3799 if (BaseClassDecl->isInvalidDecl())
3800 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003801 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003802 continue;
John McCall58e6f342010-03-16 05:22:47 +00003803
Douglas Gregordb89f282010-07-01 22:47:18 +00003804 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003805 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003806
3807 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003808 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003809 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003810 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003811 << Base->getSourceRange(),
3812 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003813
Eli Friedman5f2987c2012-02-02 03:46:19 +00003814 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003815 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003816 }
3817
3818 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003819 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3820 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003821
3822 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003823 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003824
3825 // Ignore direct virtual bases.
3826 if (DirectVirtualBases.count(RT))
3827 continue;
3828
John McCall58e6f342010-03-16 05:22:47 +00003829 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003830 // If our base class is invalid, we probably can't get its dtor anyway.
3831 if (BaseClassDecl->isInvalidDecl())
3832 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003833 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003834 continue;
John McCall58e6f342010-03-16 05:22:47 +00003835
Douglas Gregordb89f282010-07-01 22:47:18 +00003836 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003837 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003838 if (CheckDestructorAccess(
3839 ClassDecl->getLocation(), Dtor,
3840 PDiag(diag::err_access_dtor_vbase)
3841 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3842 Context.getTypeDeclType(ClassDecl)) ==
3843 AR_accessible) {
3844 CheckDerivedToBaseConversion(
3845 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3846 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3847 SourceRange(), DeclarationName(), 0);
3848 }
John McCall58e6f342010-03-16 05:22:47 +00003849
Eli Friedman5f2987c2012-02-02 03:46:19 +00003850 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003851 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003852 }
3853}
3854
John McCalld226f652010-08-21 09:40:31 +00003855void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003856 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003857 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Mike Stump1eb44332009-09-09 15:08:12 +00003859 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003860 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003861 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003862}
3863
Mike Stump1eb44332009-09-09 15:08:12 +00003864bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003865 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003866 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3867 unsigned DiagID;
3868 AbstractDiagSelID SelID;
3869
3870 public:
3871 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3872 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3873
3874 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003875 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003876 if (SelID == -1)
3877 S.Diag(Loc, DiagID) << T;
3878 else
3879 S.Diag(Loc, DiagID) << SelID << T;
3880 }
3881 } Diagnoser(DiagID, SelID);
3882
3883 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003884}
3885
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003886bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003887 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003888 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003889 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Anders Carlsson11f21a02009-03-23 19:10:31 +00003891 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003892 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Ted Kremenek6217b802009-07-29 21:53:49 +00003894 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003895 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003896 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003897 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003899 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003900 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003901 }
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Ted Kremenek6217b802009-07-29 21:53:49 +00003903 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003904 if (!RT)
3905 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003906
John McCall86ff3082010-02-04 22:26:26 +00003907 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003908
John McCall94c3b562010-08-18 09:41:07 +00003909 // We can't answer whether something is abstract until it has a
3910 // definition. If it's currently being defined, we'll walk back
3911 // over all the declarations when we have a full definition.
3912 const CXXRecordDecl *Def = RD->getDefinition();
3913 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003914 return false;
3915
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003916 if (!RD->isAbstract())
3917 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003919 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003920 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003921
John McCall94c3b562010-08-18 09:41:07 +00003922 return true;
3923}
3924
3925void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3926 // Check if we've already emitted the list of pure virtual functions
3927 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003928 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003929 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Richard Smithcbc820a2013-07-22 02:56:56 +00003931 // If the diagnostic is suppressed, don't emit the notes. We're only
3932 // going to emit them once, so try to attach them to a diagnostic we're
3933 // actually going to show.
3934 if (Diags.isLastDiagnosticIgnored())
3935 return;
3936
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003937 CXXFinalOverriderMap FinalOverriders;
3938 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003940 // Keep a set of seen pure methods so we won't diagnose the same method
3941 // more than once.
3942 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3943
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003944 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3945 MEnd = FinalOverriders.end();
3946 M != MEnd;
3947 ++M) {
3948 for (OverridingMethods::iterator SO = M->second.begin(),
3949 SOEnd = M->second.end();
3950 SO != SOEnd; ++SO) {
3951 // C++ [class.abstract]p4:
3952 // A class is abstract if it contains or inherits at least one
3953 // pure virtual function for which the final overrider is pure
3954 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003956 //
3957 if (SO->second.size() != 1)
3958 continue;
3959
3960 if (!SO->second.front().Method->isPure())
3961 continue;
3962
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003963 if (!SeenPureMethods.insert(SO->second.front().Method))
3964 continue;
3965
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003966 Diag(SO->second.front().Method->getLocation(),
3967 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003968 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003969 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003970 }
3971
3972 if (!PureVirtualClassDiagSet)
3973 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3974 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003975}
3976
Anders Carlsson8211eff2009-03-24 01:19:16 +00003977namespace {
John McCall94c3b562010-08-18 09:41:07 +00003978struct AbstractUsageInfo {
3979 Sema &S;
3980 CXXRecordDecl *Record;
3981 CanQualType AbstractType;
3982 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003983
John McCall94c3b562010-08-18 09:41:07 +00003984 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3985 : S(S), Record(Record),
3986 AbstractType(S.Context.getCanonicalType(
3987 S.Context.getTypeDeclType(Record))),
3988 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003989
John McCall94c3b562010-08-18 09:41:07 +00003990 void DiagnoseAbstractType() {
3991 if (Invalid) return;
3992 S.DiagnoseAbstractType(Record);
3993 Invalid = true;
3994 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003995
John McCall94c3b562010-08-18 09:41:07 +00003996 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3997};
3998
3999struct CheckAbstractUsage {
4000 AbstractUsageInfo &Info;
4001 const NamedDecl *Ctx;
4002
4003 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4004 : Info(Info), Ctx(Ctx) {}
4005
4006 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4007 switch (TL.getTypeLocClass()) {
4008#define ABSTRACT_TYPELOC(CLASS, PARENT)
4009#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004010 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004011#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004012 }
John McCall94c3b562010-08-18 09:41:07 +00004013 }
Mike Stump1eb44332009-09-09 15:08:12 +00004014
John McCall94c3b562010-08-18 09:41:07 +00004015 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4016 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4017 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004018 if (!TL.getArg(I))
4019 continue;
4020
John McCall94c3b562010-08-18 09:41:07 +00004021 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4022 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004023 }
John McCall94c3b562010-08-18 09:41:07 +00004024 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004025
John McCall94c3b562010-08-18 09:41:07 +00004026 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4027 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4028 }
Mike Stump1eb44332009-09-09 15:08:12 +00004029
John McCall94c3b562010-08-18 09:41:07 +00004030 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4031 // Visit the type parameters from a permissive context.
4032 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4033 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4034 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4035 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4036 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4037 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004038 }
John McCall94c3b562010-08-18 09:41:07 +00004039 }
Mike Stump1eb44332009-09-09 15:08:12 +00004040
John McCall94c3b562010-08-18 09:41:07 +00004041 // Visit pointee types from a permissive context.
4042#define CheckPolymorphic(Type) \
4043 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4044 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4045 }
4046 CheckPolymorphic(PointerTypeLoc)
4047 CheckPolymorphic(ReferenceTypeLoc)
4048 CheckPolymorphic(MemberPointerTypeLoc)
4049 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004050 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004051
John McCall94c3b562010-08-18 09:41:07 +00004052 /// Handle all the types we haven't given a more specific
4053 /// implementation for above.
4054 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4055 // Every other kind of type that we haven't called out already
4056 // that has an inner type is either (1) sugar or (2) contains that
4057 // inner type in some way as a subobject.
4058 if (TypeLoc Next = TL.getNextTypeLoc())
4059 return Visit(Next, Sel);
4060
4061 // If there's no inner type and we're in a permissive context,
4062 // don't diagnose.
4063 if (Sel == Sema::AbstractNone) return;
4064
4065 // Check whether the type matches the abstract type.
4066 QualType T = TL.getType();
4067 if (T->isArrayType()) {
4068 Sel = Sema::AbstractArrayType;
4069 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004070 }
John McCall94c3b562010-08-18 09:41:07 +00004071 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4072 if (CT != Info.AbstractType) return;
4073
4074 // It matched; do some magic.
4075 if (Sel == Sema::AbstractArrayType) {
4076 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4077 << T << TL.getSourceRange();
4078 } else {
4079 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4080 << Sel << T << TL.getSourceRange();
4081 }
4082 Info.DiagnoseAbstractType();
4083 }
4084};
4085
4086void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4087 Sema::AbstractDiagSelID Sel) {
4088 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4089}
4090
4091}
4092
4093/// Check for invalid uses of an abstract type in a method declaration.
4094static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4095 CXXMethodDecl *MD) {
4096 // No need to do the check on definitions, which require that
4097 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004098 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004099 return;
4100
4101 // For safety's sake, just ignore it if we don't have type source
4102 // information. This should never happen for non-implicit methods,
4103 // but...
4104 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4105 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4106}
4107
4108/// Check for invalid uses of an abstract type within a class definition.
4109static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4110 CXXRecordDecl *RD) {
4111 for (CXXRecordDecl::decl_iterator
4112 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4113 Decl *D = *I;
4114 if (D->isImplicit()) continue;
4115
4116 // Methods and method templates.
4117 if (isa<CXXMethodDecl>(D)) {
4118 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4119 } else if (isa<FunctionTemplateDecl>(D)) {
4120 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4121 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4122
4123 // Fields and static variables.
4124 } else if (isa<FieldDecl>(D)) {
4125 FieldDecl *FD = cast<FieldDecl>(D);
4126 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4127 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4128 } else if (isa<VarDecl>(D)) {
4129 VarDecl *VD = cast<VarDecl>(D);
4130 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4131 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4132
4133 // Nested classes and class templates.
4134 } else if (isa<CXXRecordDecl>(D)) {
4135 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4136 } else if (isa<ClassTemplateDecl>(D)) {
4137 CheckAbstractClassUsage(Info,
4138 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4139 }
4140 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004141}
4142
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004143/// \brief Perform semantic checks on a class definition that has been
4144/// completing, introducing implicitly-declared members, checking for
4145/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004146void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004147 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004148 return;
4149
John McCall94c3b562010-08-18 09:41:07 +00004150 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4151 AbstractUsageInfo Info(*this, Record);
4152 CheckAbstractClassUsage(Info, Record);
4153 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004154
4155 // If this is not an aggregate type and has no user-declared constructor,
4156 // complain about any non-static data members of reference or const scalar
4157 // type, since they will never get initializers.
4158 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004159 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4160 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004161 bool Complained = false;
4162 for (RecordDecl::field_iterator F = Record->field_begin(),
4163 FEnd = Record->field_end();
4164 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004165 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004166 continue;
4167
Douglas Gregor325e5932010-04-15 00:00:53 +00004168 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004169 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004170 if (!Complained) {
4171 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4172 << Record->getTagKind() << Record;
4173 Complained = true;
4174 }
4175
4176 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4177 << F->getType()->isReferenceType()
4178 << F->getDeclName();
4179 }
4180 }
4181 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004182
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004183 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004184 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004185
4186 if (Record->getIdentifier()) {
4187 // C++ [class.mem]p13:
4188 // If T is the name of a class, then each of the following shall have a
4189 // name different from T:
4190 // - every member of every anonymous union that is a member of class T.
4191 //
4192 // C++ [class.mem]p14:
4193 // In addition, if class T has a user-declared constructor (12.1), every
4194 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004195 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4196 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4197 ++I) {
4198 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004199 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4200 isa<IndirectFieldDecl>(D)) {
4201 Diag(D->getLocation(), diag::err_member_name_of_class)
4202 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004203 break;
4204 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004205 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004206 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004207
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004208 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004209 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004210 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004211 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004212 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4213 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4214 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004215
David Blaikieb6b5b972012-09-21 03:21:07 +00004216 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4217 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4218 DiagnoseAbstractType(Record);
4219 }
4220
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004221 if (!Record->isDependentType()) {
4222 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4223 MEnd = Record->method_end();
4224 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004225 // See if a method overloads virtual methods in a base
4226 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004227 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004228 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004229
4230 // Check whether the explicitly-defaulted special members are valid.
4231 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4232 CheckExplicitlyDefaultedSpecialMember(*M);
4233
4234 // For an explicitly defaulted or deleted special member, we defer
4235 // determining triviality until the class is complete. That time is now!
4236 if (!M->isImplicit() && !M->isUserProvided()) {
4237 CXXSpecialMember CSM = getSpecialMember(*M);
4238 if (CSM != CXXInvalid) {
4239 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4240
4241 // Inform the class that we've finished declaring this member.
4242 Record->finishedDefaultedOrDeletedMember(*M);
4243 }
4244 }
4245 }
4246 }
4247
4248 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4249 // function that is not a constructor declares that member function to be
4250 // const. [...] The class of which that function is a member shall be
4251 // a literal type.
4252 //
4253 // If the class has virtual bases, any constexpr members will already have
4254 // been diagnosed by the checks performed on the member declaration, so
4255 // suppress this (less useful) diagnostic.
4256 //
4257 // We delay this until we know whether an explicitly-defaulted (or deleted)
4258 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004259 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004260 !Record->isLiteral() && !Record->getNumVBases()) {
4261 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4262 MEnd = Record->method_end();
4263 M != MEnd; ++M) {
4264 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4265 switch (Record->getTemplateSpecializationKind()) {
4266 case TSK_ImplicitInstantiation:
4267 case TSK_ExplicitInstantiationDeclaration:
4268 case TSK_ExplicitInstantiationDefinition:
4269 // If a template instantiates to a non-literal type, but its members
4270 // instantiate to constexpr functions, the template is technically
4271 // ill-formed, but we allow it for sanity.
4272 continue;
4273
4274 case TSK_Undeclared:
4275 case TSK_ExplicitSpecialization:
4276 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4277 diag::err_constexpr_method_non_literal);
4278 break;
4279 }
4280
4281 // Only produce one error per class.
4282 break;
4283 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004284 }
4285 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004286
Richard Smith07b0fdc2013-03-18 21:12:30 +00004287 // Declare inheriting constructors. We do this eagerly here because:
4288 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004289 // constructors from different classes.
4290 // - The lazy declaration of the other implicit constructors is so as to not
4291 // waste space and performance on classes that are not meant to be
4292 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004293 // have inheriting constructors.
4294 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004295}
4296
Richard Smith7756afa2012-06-10 05:43:50 +00004297/// Is the special member function which would be selected to perform the
4298/// specified operation on the specified class type a constexpr constructor?
4299static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4300 Sema::CXXSpecialMember CSM,
4301 bool ConstArg) {
4302 Sema::SpecialMemberOverloadResult *SMOR =
4303 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4304 false, false, false, false);
4305 if (!SMOR || !SMOR->getMethod())
4306 // A constructor we wouldn't select can't be "involved in initializing"
4307 // anything.
4308 return true;
4309 return SMOR->getMethod()->isConstexpr();
4310}
4311
4312/// Determine whether the specified special member function would be constexpr
4313/// if it were implicitly defined.
4314static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4315 Sema::CXXSpecialMember CSM,
4316 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004317 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004318 return false;
4319
4320 // C++11 [dcl.constexpr]p4:
4321 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004322 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004323 switch (CSM) {
4324 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004325 // Since default constructor lookup is essentially trivial (and cannot
4326 // involve, for instance, template instantiation), we compute whether a
4327 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4328 //
4329 // This is important for performance; we need to know whether the default
4330 // constructor is constexpr to determine whether the type is a literal type.
4331 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4332
Richard Smith7756afa2012-06-10 05:43:50 +00004333 case Sema::CXXCopyConstructor:
4334 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004335 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004336 break;
4337
4338 case Sema::CXXCopyAssignment:
4339 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004340 if (!S.getLangOpts().CPlusPlus1y)
4341 return false;
4342 // In C++1y, we need to perform overload resolution.
4343 Ctor = false;
4344 break;
4345
Richard Smith7756afa2012-06-10 05:43:50 +00004346 case Sema::CXXDestructor:
4347 case Sema::CXXInvalid:
4348 return false;
4349 }
4350
4351 // -- if the class is a non-empty union, or for each non-empty anonymous
4352 // union member of a non-union class, exactly one non-static data member
4353 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004354 //
4355 // If we squint, this is guaranteed, since exactly one non-static data member
4356 // will be initialized (if the constructor isn't deleted), we just don't know
4357 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004358 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004359 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004360
4361 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004362 if (Ctor && ClassDecl->getNumVBases())
4363 return false;
4364
4365 // C++1y [class.copy]p26:
4366 // -- [the class] is a literal type, and
4367 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004368 return false;
4369
4370 // -- every constructor involved in initializing [...] base class
4371 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004372 // -- the assignment operator selected to copy/move each direct base
4373 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004374 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4375 BEnd = ClassDecl->bases_end();
4376 B != BEnd; ++B) {
4377 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4378 if (!BaseType) continue;
4379
4380 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4381 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4382 return false;
4383 }
4384
4385 // -- every constructor involved in initializing non-static data members
4386 // [...] shall be a constexpr constructor;
4387 // -- every non-static data member and base class sub-object shall be
4388 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004389 // -- for each non-stastic data member of X that is of class type (or array
4390 // thereof), the assignment operator selected to copy/move that member is
4391 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004392 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4393 FEnd = ClassDecl->field_end();
4394 F != FEnd; ++F) {
4395 if (F->isInvalidDecl())
4396 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004397 if (const RecordType *RecordTy =
4398 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004399 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4400 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4401 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004402 }
4403 }
4404
4405 // All OK, it's constexpr!
4406 return true;
4407}
4408
Richard Smithb9d0b762012-07-27 04:22:15 +00004409static Sema::ImplicitExceptionSpecification
4410computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4411 switch (S.getSpecialMember(MD)) {
4412 case Sema::CXXDefaultConstructor:
4413 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4414 case Sema::CXXCopyConstructor:
4415 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4416 case Sema::CXXCopyAssignment:
4417 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4418 case Sema::CXXMoveConstructor:
4419 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4420 case Sema::CXXMoveAssignment:
4421 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4422 case Sema::CXXDestructor:
4423 return S.ComputeDefaultedDtorExceptionSpec(MD);
4424 case Sema::CXXInvalid:
4425 break;
4426 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004427 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4428 "only special members have implicit exception specs");
4429 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004430}
4431
Richard Smithdd25e802012-07-30 23:48:14 +00004432static void
4433updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4434 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4435 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4436 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004437 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4438 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004439}
4440
Richard Smithb9d0b762012-07-27 04:22:15 +00004441void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4442 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4443 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4444 return;
4445
Richard Smithdd25e802012-07-30 23:48:14 +00004446 // Evaluate the exception specification.
4447 ImplicitExceptionSpecification ExceptSpec =
4448 computeImplicitExceptionSpec(*this, Loc, MD);
4449
4450 // Update the type of the special member to use it.
4451 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4452
4453 // A user-provided destructor can be defined outside the class. When that
4454 // happens, be sure to update the exception specification on both
4455 // declarations.
4456 const FunctionProtoType *CanonicalFPT =
4457 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4458 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4459 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4460 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004461}
4462
Richard Smith3003e1d2012-05-15 04:39:51 +00004463void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4464 CXXRecordDecl *RD = MD->getParent();
4465 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004466
Richard Smith3003e1d2012-05-15 04:39:51 +00004467 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4468 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004469
4470 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004471 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004472 bool First = MD == MD->getCanonicalDecl();
4473
4474 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004475
4476 // C++11 [dcl.fct.def.default]p1:
4477 // A function that is explicitly defaulted shall
4478 // -- be a special member function (checked elsewhere),
4479 // -- have the same type (except for ref-qualifiers, and except that a
4480 // copy operation can take a non-const reference) as an implicit
4481 // declaration, and
4482 // -- not have default arguments.
4483 unsigned ExpectedParams = 1;
4484 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4485 ExpectedParams = 0;
4486 if (MD->getNumParams() != ExpectedParams) {
4487 // This also checks for default arguments: a copy or move constructor with a
4488 // default argument is classified as a default constructor, and assignment
4489 // operations and destructors can't have default arguments.
4490 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4491 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004492 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004493 } else if (MD->isVariadic()) {
4494 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4495 << CSM << MD->getSourceRange();
4496 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004497 }
4498
Richard Smith3003e1d2012-05-15 04:39:51 +00004499 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004500
Richard Smith7756afa2012-06-10 05:43:50 +00004501 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004502 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004503 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004504 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004505 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004506
Richard Smith3003e1d2012-05-15 04:39:51 +00004507 QualType ReturnType = Context.VoidTy;
4508 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4509 // Check for return type matching.
4510 ReturnType = Type->getResultType();
4511 QualType ExpectedReturnType =
4512 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4513 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4514 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4515 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4516 HadError = true;
4517 }
4518
4519 // A defaulted special member cannot have cv-qualifiers.
4520 if (Type->getTypeQuals()) {
4521 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004522 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004523 HadError = true;
4524 }
4525 }
4526
4527 // Check for parameter type matching.
4528 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004529 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004530 if (ExpectedParams && ArgType->isReferenceType()) {
4531 // Argument must be reference to possibly-const T.
4532 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004533 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004534
4535 if (ReferentType.isVolatileQualified()) {
4536 Diag(MD->getLocation(),
4537 diag::err_defaulted_special_member_volatile_param) << CSM;
4538 HadError = true;
4539 }
4540
Richard Smith7756afa2012-06-10 05:43:50 +00004541 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004542 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4543 Diag(MD->getLocation(),
4544 diag::err_defaulted_special_member_copy_const_param)
4545 << (CSM == CXXCopyAssignment);
4546 // FIXME: Explain why this special member can't be const.
4547 } else {
4548 Diag(MD->getLocation(),
4549 diag::err_defaulted_special_member_move_const_param)
4550 << (CSM == CXXMoveAssignment);
4551 }
4552 HadError = true;
4553 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004554 } else if (ExpectedParams) {
4555 // A copy assignment operator can take its argument by value, but a
4556 // defaulted one cannot.
4557 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004558 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004559 HadError = true;
4560 }
Sean Huntbe631222011-05-17 20:44:43 +00004561
Richard Smith61802452011-12-22 02:22:31 +00004562 // C++11 [dcl.fct.def.default]p2:
4563 // An explicitly-defaulted function may be declared constexpr only if it
4564 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004565 // Do not apply this rule to members of class templates, since core issue 1358
4566 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004567 // functions which cannot be constexpr (for non-constructors in C++11 and for
4568 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004569 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4570 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004571 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4572 : isa<CXXConstructorDecl>(MD)) &&
4573 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004574 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4575 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004576 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004577 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004578 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004579
Richard Smith61802452011-12-22 02:22:31 +00004580 // and may have an explicit exception-specification only if it is compatible
4581 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004582 if (Type->hasExceptionSpec()) {
4583 // Delay the check if this is the first declaration of the special member,
4584 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004585 if (First) {
4586 // If the exception specification needs to be instantiated, do so now,
4587 // before we clobber it with an EST_Unevaluated specification below.
4588 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4589 InstantiateExceptionSpec(MD->getLocStart(), MD);
4590 Type = MD->getType()->getAs<FunctionProtoType>();
4591 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004592 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004593 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004594 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4595 }
Richard Smith61802452011-12-22 02:22:31 +00004596
4597 // If a function is explicitly defaulted on its first declaration,
4598 if (First) {
4599 // -- it is implicitly considered to be constexpr if the implicit
4600 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004601 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004602
Richard Smith3003e1d2012-05-15 04:39:51 +00004603 // -- it is implicitly considered to have the same exception-specification
4604 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004605 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4606 EPI.ExceptionSpecType = EST_Unevaluated;
4607 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004608 MD->setType(Context.getFunctionType(ReturnType,
4609 ArrayRef<QualType>(&ArgType,
4610 ExpectedParams),
4611 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004612 }
4613
Richard Smith3003e1d2012-05-15 04:39:51 +00004614 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004615 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004616 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004617 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004618 // C++11 [dcl.fct.def.default]p4:
4619 // [For a] user-provided explicitly-defaulted function [...] if such a
4620 // function is implicitly defined as deleted, the program is ill-formed.
4621 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4622 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004623 }
4624 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004625
Richard Smith3003e1d2012-05-15 04:39:51 +00004626 if (HadError)
4627 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004628}
4629
Richard Smith1d28caf2012-12-11 01:14:52 +00004630/// Check whether the exception specification provided for an
4631/// explicitly-defaulted special member matches the exception specification
4632/// that would have been generated for an implicit special member, per
4633/// C++11 [dcl.fct.def.default]p2.
4634void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4635 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4636 // Compute the implicit exception specification.
4637 FunctionProtoType::ExtProtoInfo EPI;
4638 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4639 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004640 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004641
4642 // Ensure that it matches.
4643 CheckEquivalentExceptionSpec(
4644 PDiag(diag::err_incorrect_defaulted_exception_spec)
4645 << getSpecialMember(MD), PDiag(),
4646 ImplicitType, SourceLocation(),
4647 SpecifiedType, MD->getLocation());
4648}
4649
4650void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4651 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4652 I != N; ++I)
4653 CheckExplicitlyDefaultedMemberExceptionSpec(
4654 DelayedDefaultedMemberExceptionSpecs[I].first,
4655 DelayedDefaultedMemberExceptionSpecs[I].second);
4656
4657 DelayedDefaultedMemberExceptionSpecs.clear();
4658}
4659
Richard Smith7d5088a2012-02-18 02:02:13 +00004660namespace {
4661struct SpecialMemberDeletionInfo {
4662 Sema &S;
4663 CXXMethodDecl *MD;
4664 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004665 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004666
4667 // Properties of the special member, computed for convenience.
4668 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4669 SourceLocation Loc;
4670
4671 bool AllFieldsAreConst;
4672
4673 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004674 Sema::CXXSpecialMember CSM, bool Diagnose)
4675 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004676 IsConstructor(false), IsAssignment(false), IsMove(false),
4677 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4678 AllFieldsAreConst(true) {
4679 switch (CSM) {
4680 case Sema::CXXDefaultConstructor:
4681 case Sema::CXXCopyConstructor:
4682 IsConstructor = true;
4683 break;
4684 case Sema::CXXMoveConstructor:
4685 IsConstructor = true;
4686 IsMove = true;
4687 break;
4688 case Sema::CXXCopyAssignment:
4689 IsAssignment = true;
4690 break;
4691 case Sema::CXXMoveAssignment:
4692 IsAssignment = true;
4693 IsMove = true;
4694 break;
4695 case Sema::CXXDestructor:
4696 break;
4697 case Sema::CXXInvalid:
4698 llvm_unreachable("invalid special member kind");
4699 }
4700
4701 if (MD->getNumParams()) {
4702 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4703 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4704 }
4705 }
4706
4707 bool inUnion() const { return MD->getParent()->isUnion(); }
4708
4709 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004710 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4711 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004712 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004713 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4714 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4715 Quals = 0;
4716 return S.LookupSpecialMember(Class, CSM,
4717 ConstArg || (Quals & Qualifiers::Const),
4718 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004719 MD->getRefQualifier() == RQ_RValue,
4720 TQ & Qualifiers::Const,
4721 TQ & Qualifiers::Volatile);
4722 }
4723
Richard Smith6c4c36c2012-03-30 20:53:28 +00004724 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004725
Richard Smith6c4c36c2012-03-30 20:53:28 +00004726 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004727 bool shouldDeleteForField(FieldDecl *FD);
4728 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004729
Richard Smith517bb842012-07-18 03:51:16 +00004730 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4731 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4733 Sema::SpecialMemberOverloadResult *SMOR,
4734 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004735
4736 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004737};
4738}
4739
John McCall12d8d802012-04-09 20:53:23 +00004740/// Is the given special member inaccessible when used on the given
4741/// sub-object.
4742bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4743 CXXMethodDecl *target) {
4744 /// If we're operating on a base class, the object type is the
4745 /// type of this special member.
4746 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004747 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004748 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4749 objectTy = S.Context.getTypeDeclType(MD->getParent());
4750 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4751
4752 // If we're operating on a field, the object type is the type of the field.
4753 } else {
4754 objectTy = S.Context.getTypeDeclType(target->getParent());
4755 }
4756
4757 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4758}
4759
Richard Smith6c4c36c2012-03-30 20:53:28 +00004760/// Check whether we should delete a special member due to the implicit
4761/// definition containing a call to a special member of a subobject.
4762bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4763 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4764 bool IsDtorCallInCtor) {
4765 CXXMethodDecl *Decl = SMOR->getMethod();
4766 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4767
4768 int DiagKind = -1;
4769
4770 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4771 DiagKind = !Decl ? 0 : 1;
4772 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4773 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004774 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004775 DiagKind = 3;
4776 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4777 !Decl->isTrivial()) {
4778 // A member of a union must have a trivial corresponding special member.
4779 // As a weird special case, a destructor call from a union's constructor
4780 // must be accessible and non-deleted, but need not be trivial. Such a
4781 // destructor is never actually called, but is semantically checked as
4782 // if it were.
4783 DiagKind = 4;
4784 }
4785
4786 if (DiagKind == -1)
4787 return false;
4788
4789 if (Diagnose) {
4790 if (Field) {
4791 S.Diag(Field->getLocation(),
4792 diag::note_deleted_special_member_class_subobject)
4793 << CSM << MD->getParent() << /*IsField*/true
4794 << Field << DiagKind << IsDtorCallInCtor;
4795 } else {
4796 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4797 S.Diag(Base->getLocStart(),
4798 diag::note_deleted_special_member_class_subobject)
4799 << CSM << MD->getParent() << /*IsField*/false
4800 << Base->getType() << DiagKind << IsDtorCallInCtor;
4801 }
4802
4803 if (DiagKind == 1)
4804 S.NoteDeletedFunction(Decl);
4805 // FIXME: Explain inaccessibility if DiagKind == 3.
4806 }
4807
4808 return true;
4809}
4810
Richard Smith9a561d52012-02-26 09:11:52 +00004811/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004812/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004813bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004814 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004815 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004816
4817 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004818 // -- any direct or virtual base class, or non-static data member with no
4819 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004820 // either M has no default constructor or overload resolution as applied
4821 // to M's default constructor results in an ambiguity or in a function
4822 // that is deleted or inaccessible
4823 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4824 // -- a direct or virtual base class B that cannot be copied/moved because
4825 // overload resolution, as applied to B's corresponding special member,
4826 // results in an ambiguity or a function that is deleted or inaccessible
4827 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004828 // C++11 [class.dtor]p5:
4829 // -- any direct or virtual base class [...] has a type with a destructor
4830 // that is deleted or inaccessible
4831 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004832 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004833 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004834 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004835
Richard Smith6c4c36c2012-03-30 20:53:28 +00004836 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4837 // -- any direct or virtual base class or non-static data member has a
4838 // type with a destructor that is deleted or inaccessible
4839 if (IsConstructor) {
4840 Sema::SpecialMemberOverloadResult *SMOR =
4841 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4842 false, false, false, false, false);
4843 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4844 return true;
4845 }
4846
Richard Smith9a561d52012-02-26 09:11:52 +00004847 return false;
4848}
4849
4850/// Check whether we should delete a special member function due to the class
4851/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004852bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004853 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004854 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004855}
4856
4857/// Check whether we should delete a special member function due to the class
4858/// having a particular non-static data member.
4859bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4860 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4861 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4862
4863 if (CSM == Sema::CXXDefaultConstructor) {
4864 // For a default constructor, all references must be initialized in-class
4865 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004866 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4867 if (Diagnose)
4868 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4869 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004871 }
Richard Smith79363f52012-02-27 06:07:25 +00004872 // C++11 [class.ctor]p5: any non-variant non-static data member of
4873 // const-qualified type (or array thereof) with no
4874 // brace-or-equal-initializer does not have a user-provided default
4875 // constructor.
4876 if (!inUnion() && FieldType.isConstQualified() &&
4877 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004878 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4879 if (Diagnose)
4880 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004881 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004882 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004883 }
4884
4885 if (inUnion() && !FieldType.isConstQualified())
4886 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004887 } else if (CSM == Sema::CXXCopyConstructor) {
4888 // For a copy constructor, data members must not be of rvalue reference
4889 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004890 if (FieldType->isRValueReferenceType()) {
4891 if (Diagnose)
4892 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4893 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004894 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004895 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004896 } else if (IsAssignment) {
4897 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004898 if (FieldType->isReferenceType()) {
4899 if (Diagnose)
4900 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4901 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004902 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004903 }
4904 if (!FieldRecord && FieldType.isConstQualified()) {
4905 // C++11 [class.copy]p23:
4906 // -- a non-static data member of const non-class type (or array thereof)
4907 if (Diagnose)
4908 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004909 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004910 return true;
4911 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004912 }
4913
4914 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004915 // Some additional restrictions exist on the variant members.
4916 if (!inUnion() && FieldRecord->isUnion() &&
4917 FieldRecord->isAnonymousStructOrUnion()) {
4918 bool AllVariantFieldsAreConst = true;
4919
Richard Smithdf8dc862012-03-29 19:00:10 +00004920 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004921 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4922 UE = FieldRecord->field_end();
4923 UI != UE; ++UI) {
4924 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004925
4926 if (!UnionFieldType.isConstQualified())
4927 AllVariantFieldsAreConst = false;
4928
Richard Smith9a561d52012-02-26 09:11:52 +00004929 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4930 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004931 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4932 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004933 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004934 }
4935
4936 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004937 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004938 FieldRecord->field_begin() != FieldRecord->field_end()) {
4939 if (Diagnose)
4940 S.Diag(FieldRecord->getLocation(),
4941 diag::note_deleted_default_ctor_all_const)
4942 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004943 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004944 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004945
Richard Smithdf8dc862012-03-29 19:00:10 +00004946 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004947 // This is technically non-conformant, but sanity demands it.
4948 return false;
4949 }
4950
Richard Smith517bb842012-07-18 03:51:16 +00004951 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4952 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004953 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004954 }
4955
4956 return false;
4957}
4958
4959/// C++11 [class.ctor] p5:
4960/// A defaulted default constructor for a class X is defined as deleted if
4961/// X is a union and all of its variant members are of const-qualified type.
4962bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004963 // This is a silly definition, because it gives an empty union a deleted
4964 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004965 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4966 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4967 if (Diagnose)
4968 S.Diag(MD->getParent()->getLocation(),
4969 diag::note_deleted_default_ctor_all_const)
4970 << MD->getParent() << /*not anonymous union*/0;
4971 return true;
4972 }
4973 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004974}
4975
4976/// Determine whether a defaulted special member function should be defined as
4977/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4978/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004979bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4980 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004981 if (MD->isInvalidDecl())
4982 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004983 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004984 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004985 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004986 return false;
4987
Richard Smith7d5088a2012-02-18 02:02:13 +00004988 // C++11 [expr.lambda.prim]p19:
4989 // The closure type associated with a lambda-expression has a
4990 // deleted (8.4.3) default constructor and a deleted copy
4991 // assignment operator.
4992 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004993 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4994 if (Diagnose)
4995 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004996 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004997 }
4998
Richard Smith5bdaac52012-04-02 20:59:25 +00004999 // For an anonymous struct or union, the copy and assignment special members
5000 // will never be used, so skip the check. For an anonymous union declared at
5001 // namespace scope, the constructor and destructor are used.
5002 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5003 RD->isAnonymousStructOrUnion())
5004 return false;
5005
Richard Smith6c4c36c2012-03-30 20:53:28 +00005006 // C++11 [class.copy]p7, p18:
5007 // If the class definition declares a move constructor or move assignment
5008 // operator, an implicitly declared copy constructor or copy assignment
5009 // operator is defined as deleted.
5010 if (MD->isImplicit() &&
5011 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5012 CXXMethodDecl *UserDeclaredMove = 0;
5013
5014 // In Microsoft mode, a user-declared move only causes the deletion of the
5015 // corresponding copy operation, not both copy operations.
5016 if (RD->hasUserDeclaredMoveConstructor() &&
5017 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5018 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005019
5020 // Find any user-declared move constructor.
5021 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5022 E = RD->ctor_end(); I != E; ++I) {
5023 if (I->isMoveConstructor()) {
5024 UserDeclaredMove = *I;
5025 break;
5026 }
5027 }
Richard Smith1c931be2012-04-02 18:40:40 +00005028 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005029 } else if (RD->hasUserDeclaredMoveAssignment() &&
5030 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5031 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005032
5033 // Find any user-declared move assignment operator.
5034 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5035 E = RD->method_end(); I != E; ++I) {
5036 if (I->isMoveAssignmentOperator()) {
5037 UserDeclaredMove = *I;
5038 break;
5039 }
5040 }
Richard Smith1c931be2012-04-02 18:40:40 +00005041 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005042 }
5043
5044 if (UserDeclaredMove) {
5045 Diag(UserDeclaredMove->getLocation(),
5046 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005047 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005048 << UserDeclaredMove->isMoveAssignmentOperator();
5049 return true;
5050 }
5051 }
Sean Hunte16da072011-10-10 06:18:57 +00005052
Richard Smith5bdaac52012-04-02 20:59:25 +00005053 // Do access control from the special member function
5054 ContextRAII MethodContext(*this, MD);
5055
Richard Smith9a561d52012-02-26 09:11:52 +00005056 // C++11 [class.dtor]p5:
5057 // -- for a virtual destructor, lookup of the non-array deallocation function
5058 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005059 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005060 FunctionDecl *OperatorDelete = 0;
5061 DeclarationName Name =
5062 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5063 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005064 OperatorDelete, false)) {
5065 if (Diagnose)
5066 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005067 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005068 }
Richard Smith9a561d52012-02-26 09:11:52 +00005069 }
5070
Richard Smith6c4c36c2012-03-30 20:53:28 +00005071 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005072
Sean Huntcdee3fe2011-05-11 22:34:38 +00005073 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005074 BE = RD->bases_end(); BI != BE; ++BI)
5075 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005076 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005077 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005078
Richard Smithcbc820a2013-07-22 02:56:56 +00005079 // Defect report (no number yet): do not consider virtual bases of
5080 // constructors of abstract classes, since we are not going to construct
5081 // them. This is an extension of DR257 into the C++11 behavior for special
5082 // members.
5083 if (!RD->isAbstract() || !SMI.IsConstructor) {
5084 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5085 BE = RD->vbases_end();
5086 BI != BE; ++BI)
5087 if (SMI.shouldDeleteForBase(BI))
5088 return true;
5089 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005090
5091 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005092 FE = RD->field_end(); FI != FE; ++FI)
5093 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005094 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005095 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005096
Richard Smith7d5088a2012-02-18 02:02:13 +00005097 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005098 return true;
5099
5100 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005101}
5102
Richard Smithac713512012-12-08 02:53:02 +00005103/// Perform lookup for a special member of the specified kind, and determine
5104/// whether it is trivial. If the triviality can be determined without the
5105/// lookup, skip it. This is intended for use when determining whether a
5106/// special member of a containing object is trivial, and thus does not ever
5107/// perform overload resolution for default constructors.
5108///
5109/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5110/// member that was most likely to be intended to be trivial, if any.
5111static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5112 Sema::CXXSpecialMember CSM, unsigned Quals,
5113 CXXMethodDecl **Selected) {
5114 if (Selected)
5115 *Selected = 0;
5116
5117 switch (CSM) {
5118 case Sema::CXXInvalid:
5119 llvm_unreachable("not a special member");
5120
5121 case Sema::CXXDefaultConstructor:
5122 // C++11 [class.ctor]p5:
5123 // A default constructor is trivial if:
5124 // - all the [direct subobjects] have trivial default constructors
5125 //
5126 // Note, no overload resolution is performed in this case.
5127 if (RD->hasTrivialDefaultConstructor())
5128 return true;
5129
5130 if (Selected) {
5131 // If there's a default constructor which could have been trivial, dig it
5132 // out. Otherwise, if there's any user-provided default constructor, point
5133 // to that as an example of why there's not a trivial one.
5134 CXXConstructorDecl *DefCtor = 0;
5135 if (RD->needsImplicitDefaultConstructor())
5136 S.DeclareImplicitDefaultConstructor(RD);
5137 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5138 CE = RD->ctor_end(); CI != CE; ++CI) {
5139 if (!CI->isDefaultConstructor())
5140 continue;
5141 DefCtor = *CI;
5142 if (!DefCtor->isUserProvided())
5143 break;
5144 }
5145
5146 *Selected = DefCtor;
5147 }
5148
5149 return false;
5150
5151 case Sema::CXXDestructor:
5152 // C++11 [class.dtor]p5:
5153 // A destructor is trivial if:
5154 // - all the direct [subobjects] have trivial destructors
5155 if (RD->hasTrivialDestructor())
5156 return true;
5157
5158 if (Selected) {
5159 if (RD->needsImplicitDestructor())
5160 S.DeclareImplicitDestructor(RD);
5161 *Selected = RD->getDestructor();
5162 }
5163
5164 return false;
5165
5166 case Sema::CXXCopyConstructor:
5167 // C++11 [class.copy]p12:
5168 // A copy constructor is trivial if:
5169 // - the constructor selected to copy each direct [subobject] is trivial
5170 if (RD->hasTrivialCopyConstructor()) {
5171 if (Quals == Qualifiers::Const)
5172 // We must either select the trivial copy constructor or reach an
5173 // ambiguity; no need to actually perform overload resolution.
5174 return true;
5175 } else if (!Selected) {
5176 return false;
5177 }
5178 // In C++98, we are not supposed to perform overload resolution here, but we
5179 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5180 // cases like B as having a non-trivial copy constructor:
5181 // struct A { template<typename T> A(T&); };
5182 // struct B { mutable A a; };
5183 goto NeedOverloadResolution;
5184
5185 case Sema::CXXCopyAssignment:
5186 // C++11 [class.copy]p25:
5187 // A copy assignment operator is trivial if:
5188 // - the assignment operator selected to copy each direct [subobject] is
5189 // trivial
5190 if (RD->hasTrivialCopyAssignment()) {
5191 if (Quals == Qualifiers::Const)
5192 return true;
5193 } else if (!Selected) {
5194 return false;
5195 }
5196 // In C++98, we are not supposed to perform overload resolution here, but we
5197 // treat that as a language defect.
5198 goto NeedOverloadResolution;
5199
5200 case Sema::CXXMoveConstructor:
5201 case Sema::CXXMoveAssignment:
5202 NeedOverloadResolution:
5203 Sema::SpecialMemberOverloadResult *SMOR =
5204 S.LookupSpecialMember(RD, CSM,
5205 Quals & Qualifiers::Const,
5206 Quals & Qualifiers::Volatile,
5207 /*RValueThis*/false, /*ConstThis*/false,
5208 /*VolatileThis*/false);
5209
5210 // The standard doesn't describe how to behave if the lookup is ambiguous.
5211 // We treat it as not making the member non-trivial, just like the standard
5212 // mandates for the default constructor. This should rarely matter, because
5213 // the member will also be deleted.
5214 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5215 return true;
5216
5217 if (!SMOR->getMethod()) {
5218 assert(SMOR->getKind() ==
5219 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5220 return false;
5221 }
5222
5223 // We deliberately don't check if we found a deleted special member. We're
5224 // not supposed to!
5225 if (Selected)
5226 *Selected = SMOR->getMethod();
5227 return SMOR->getMethod()->isTrivial();
5228 }
5229
5230 llvm_unreachable("unknown special method kind");
5231}
5232
Benjamin Kramera574c892013-02-15 12:30:38 +00005233static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005234 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5235 CI != CE; ++CI)
5236 if (!CI->isImplicit())
5237 return *CI;
5238
5239 // Look for constructor templates.
5240 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5241 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5242 if (CXXConstructorDecl *CD =
5243 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5244 return CD;
5245 }
5246
5247 return 0;
5248}
5249
5250/// The kind of subobject we are checking for triviality. The values of this
5251/// enumeration are used in diagnostics.
5252enum TrivialSubobjectKind {
5253 /// The subobject is a base class.
5254 TSK_BaseClass,
5255 /// The subobject is a non-static data member.
5256 TSK_Field,
5257 /// The object is actually the complete object.
5258 TSK_CompleteObject
5259};
5260
5261/// Check whether the special member selected for a given type would be trivial.
5262static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5263 QualType SubType,
5264 Sema::CXXSpecialMember CSM,
5265 TrivialSubobjectKind Kind,
5266 bool Diagnose) {
5267 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5268 if (!SubRD)
5269 return true;
5270
5271 CXXMethodDecl *Selected;
5272 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5273 Diagnose ? &Selected : 0))
5274 return true;
5275
5276 if (Diagnose) {
5277 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5278 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5279 << Kind << SubType.getUnqualifiedType();
5280 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5281 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5282 } else if (!Selected)
5283 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5284 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5285 else if (Selected->isUserProvided()) {
5286 if (Kind == TSK_CompleteObject)
5287 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5288 << Kind << SubType.getUnqualifiedType() << CSM;
5289 else {
5290 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5291 << Kind << SubType.getUnqualifiedType() << CSM;
5292 S.Diag(Selected->getLocation(), diag::note_declared_at);
5293 }
5294 } else {
5295 if (Kind != TSK_CompleteObject)
5296 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5297 << Kind << SubType.getUnqualifiedType() << CSM;
5298
5299 // Explain why the defaulted or deleted special member isn't trivial.
5300 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5301 }
5302 }
5303
5304 return false;
5305}
5306
5307/// Check whether the members of a class type allow a special member to be
5308/// trivial.
5309static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5310 Sema::CXXSpecialMember CSM,
5311 bool ConstArg, bool Diagnose) {
5312 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5313 FE = RD->field_end(); FI != FE; ++FI) {
5314 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5315 continue;
5316
5317 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5318
5319 // Pretend anonymous struct or union members are members of this class.
5320 if (FI->isAnonymousStructOrUnion()) {
5321 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5322 CSM, ConstArg, Diagnose))
5323 return false;
5324 continue;
5325 }
5326
5327 // C++11 [class.ctor]p5:
5328 // A default constructor is trivial if [...]
5329 // -- no non-static data member of its class has a
5330 // brace-or-equal-initializer
5331 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5332 if (Diagnose)
5333 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5334 return false;
5335 }
5336
5337 // Objective C ARC 4.3.5:
5338 // [...] nontrivally ownership-qualified types are [...] not trivially
5339 // default constructible, copy constructible, move constructible, copy
5340 // assignable, move assignable, or destructible [...]
5341 if (S.getLangOpts().ObjCAutoRefCount &&
5342 FieldType.hasNonTrivialObjCLifetime()) {
5343 if (Diagnose)
5344 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5345 << RD << FieldType.getObjCLifetime();
5346 return false;
5347 }
5348
5349 if (ConstArg && !FI->isMutable())
5350 FieldType.addConst();
5351 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5352 TSK_Field, Diagnose))
5353 return false;
5354 }
5355
5356 return true;
5357}
5358
5359/// Diagnose why the specified class does not have a trivial special member of
5360/// the given kind.
5361void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5362 QualType Ty = Context.getRecordType(RD);
5363 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5364 Ty.addConst();
5365
5366 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5367 TSK_CompleteObject, /*Diagnose*/true);
5368}
5369
5370/// Determine whether a defaulted or deleted special member function is trivial,
5371/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5372/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5373bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5374 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005375 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5376
5377 CXXRecordDecl *RD = MD->getParent();
5378
5379 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005380
5381 // C++11 [class.copy]p12, p25:
5382 // A [special member] is trivial if its declared parameter type is the same
5383 // as if it had been implicitly declared [...]
5384 switch (CSM) {
5385 case CXXDefaultConstructor:
5386 case CXXDestructor:
5387 // Trivial default constructors and destructors cannot have parameters.
5388 break;
5389
5390 case CXXCopyConstructor:
5391 case CXXCopyAssignment: {
5392 // Trivial copy operations always have const, non-volatile parameter types.
5393 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005394 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005395 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5396 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5397 if (Diagnose)
5398 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5399 << Param0->getSourceRange() << Param0->getType()
5400 << Context.getLValueReferenceType(
5401 Context.getRecordType(RD).withConst());
5402 return false;
5403 }
5404 break;
5405 }
5406
5407 case CXXMoveConstructor:
5408 case CXXMoveAssignment: {
5409 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005410 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005411 const RValueReferenceType *RT =
5412 Param0->getType()->getAs<RValueReferenceType>();
5413 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5414 if (Diagnose)
5415 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5416 << Param0->getSourceRange() << Param0->getType()
5417 << Context.getRValueReferenceType(Context.getRecordType(RD));
5418 return false;
5419 }
5420 break;
5421 }
5422
5423 case CXXInvalid:
5424 llvm_unreachable("not a special member");
5425 }
5426
5427 // FIXME: We require that the parameter-declaration-clause is equivalent to
5428 // that of an implicit declaration, not just that the declared parameter type
5429 // matches, in order to prevent absuridities like a function simultaneously
5430 // being a trivial copy constructor and a non-trivial default constructor.
5431 // This issue has not yet been assigned a core issue number.
5432 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5433 if (Diagnose)
5434 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5435 diag::note_nontrivial_default_arg)
5436 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5437 return false;
5438 }
5439 if (MD->isVariadic()) {
5440 if (Diagnose)
5441 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5442 return false;
5443 }
5444
5445 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5446 // A copy/move [constructor or assignment operator] is trivial if
5447 // -- the [member] selected to copy/move each direct base class subobject
5448 // is trivial
5449 //
5450 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5451 // A [default constructor or destructor] is trivial if
5452 // -- all the direct base classes have trivial [default constructors or
5453 // destructors]
5454 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5455 BE = RD->bases_end(); BI != BE; ++BI)
5456 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5457 ConstArg ? BI->getType().withConst()
5458 : BI->getType(),
5459 CSM, TSK_BaseClass, Diagnose))
5460 return false;
5461
5462 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5463 // A copy/move [constructor or assignment operator] for a class X is
5464 // trivial if
5465 // -- for each non-static data member of X that is of class type (or array
5466 // thereof), the constructor selected to copy/move that member is
5467 // trivial
5468 //
5469 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5470 // A [default constructor or destructor] is trivial if
5471 // -- for all of the non-static data members of its class that are of class
5472 // type (or array thereof), each such class has a trivial [default
5473 // constructor or destructor]
5474 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5475 return false;
5476
5477 // C++11 [class.dtor]p5:
5478 // A destructor is trivial if [...]
5479 // -- the destructor is not virtual
5480 if (CSM == CXXDestructor && MD->isVirtual()) {
5481 if (Diagnose)
5482 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5483 return false;
5484 }
5485
5486 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5487 // A [special member] for class X is trivial if [...]
5488 // -- class X has no virtual functions and no virtual base classes
5489 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5490 if (!Diagnose)
5491 return false;
5492
5493 if (RD->getNumVBases()) {
5494 // Check for virtual bases. We already know that the corresponding
5495 // member in all bases is trivial, so vbases must all be direct.
5496 CXXBaseSpecifier &BS = *RD->vbases_begin();
5497 assert(BS.isVirtual());
5498 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5499 return false;
5500 }
5501
5502 // Must have a virtual method.
5503 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5504 ME = RD->method_end(); MI != ME; ++MI) {
5505 if (MI->isVirtual()) {
5506 SourceLocation MLoc = MI->getLocStart();
5507 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5508 return false;
5509 }
5510 }
5511
5512 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5513 }
5514
5515 // Looks like it's trivial!
5516 return true;
5517}
5518
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005519/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005520namespace {
5521 struct FindHiddenVirtualMethodData {
5522 Sema *S;
5523 CXXMethodDecl *Method;
5524 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005525 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005526 };
5527}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005528
David Blaikie5f750682012-10-19 00:53:08 +00005529/// \brief Check whether any most overriden method from MD in Methods
5530static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5531 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5532 if (MD->size_overridden_methods() == 0)
5533 return Methods.count(MD->getCanonicalDecl());
5534 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5535 E = MD->end_overridden_methods();
5536 I != E; ++I)
5537 if (CheckMostOverridenMethods(*I, Methods))
5538 return true;
5539 return false;
5540}
5541
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005542/// \brief Member lookup function that determines whether a given C++
5543/// method overloads virtual methods in a base class without overriding any,
5544/// to be used with CXXRecordDecl::lookupInBases().
5545static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5546 CXXBasePath &Path,
5547 void *UserData) {
5548 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5549
5550 FindHiddenVirtualMethodData &Data
5551 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5552
5553 DeclarationName Name = Data.Method->getDeclName();
5554 assert(Name.getNameKind() == DeclarationName::Identifier);
5555
5556 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005557 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005558 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005559 !Path.Decls.empty();
5560 Path.Decls = Path.Decls.slice(1)) {
5561 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005563 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005564 foundSameNameMethod = true;
5565 // Interested only in hidden virtual methods.
5566 if (!MD->isVirtual())
5567 continue;
5568 // If the method we are checking overrides a method from its base
5569 // don't warn about the other overloaded methods.
5570 if (!Data.S->IsOverload(Data.Method, MD, false))
5571 return true;
5572 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005573 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005574 overloadedMethods.push_back(MD);
5575 }
5576 }
5577
5578 if (foundSameNameMethod)
5579 Data.OverloadedMethods.append(overloadedMethods.begin(),
5580 overloadedMethods.end());
5581 return foundSameNameMethod;
5582}
5583
David Blaikie5f750682012-10-19 00:53:08 +00005584/// \brief Add the most overriden methods from MD to Methods
5585static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5586 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5587 if (MD->size_overridden_methods() == 0)
5588 Methods.insert(MD->getCanonicalDecl());
5589 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5590 E = MD->end_overridden_methods();
5591 I != E; ++I)
5592 AddMostOverridenMethods(*I, Methods);
5593}
5594
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005595/// \brief See if a method overloads virtual methods in a base class without
5596/// overriding any.
5597void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5598 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005599 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005600 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005601 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005602 return;
5603
5604 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5605 /*bool RecordPaths=*/false,
5606 /*bool DetectVirtual=*/false);
5607 FindHiddenVirtualMethodData Data;
5608 Data.Method = MD;
5609 Data.S = this;
5610
5611 // Keep the base methods that were overriden or introduced in the subclass
5612 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005613 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5614 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5615 NamedDecl *ND = *I;
5616 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005617 ND = shad->getTargetDecl();
5618 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5619 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005620 }
5621
5622 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5623 !Data.OverloadedMethods.empty()) {
5624 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5625 << MD << (Data.OverloadedMethods.size() > 1);
5626
5627 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5628 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005629 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005630 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005631 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5632 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005633 }
5634 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005635}
5636
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005637void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005638 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005639 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005640 SourceLocation RBrac,
5641 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005642 if (!TagDecl)
5643 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005644
Douglas Gregor42af25f2009-05-11 19:58:34 +00005645 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005646
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005647 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5648 if (l->getKind() != AttributeList::AT_Visibility)
5649 continue;
5650 l->setInvalid();
5651 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5652 l->getName();
5653 }
5654
David Blaikie77b6de02011-09-22 02:58:26 +00005655 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005656 // strict aliasing violation!
5657 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005658 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005659
Douglas Gregor23c94db2010-07-02 17:43:08 +00005660 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005661 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005662}
5663
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005664/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5665/// special functions, such as the default constructor, copy
5666/// constructor, or destructor, to the given C++ class (C++
5667/// [special]p1). This routine can only be executed just before the
5668/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005669void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005670 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005671 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005672
Richard Smithbc2a35d2012-12-08 08:32:28 +00005673 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005674 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005675
Richard Smithbc2a35d2012-12-08 08:32:28 +00005676 // If the properties or semantics of the copy constructor couldn't be
5677 // determined while the class was being declared, force a declaration
5678 // of it now.
5679 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5680 DeclareImplicitCopyConstructor(ClassDecl);
5681 }
5682
Richard Smith80ad52f2013-01-02 11:42:31 +00005683 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005684 ++ASTContext::NumImplicitMoveConstructors;
5685
Richard Smithbc2a35d2012-12-08 08:32:28 +00005686 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5687 DeclareImplicitMoveConstructor(ClassDecl);
5688 }
5689
Douglas Gregora376d102010-07-02 21:50:04 +00005690 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5691 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005692
5693 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005694 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005695 // it shows up in the right place in the vtable and that we diagnose
5696 // problems with the implicit exception specification.
5697 if (ClassDecl->isDynamicClass() ||
5698 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005699 DeclareImplicitCopyAssignment(ClassDecl);
5700 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005701
Richard Smith80ad52f2013-01-02 11:42:31 +00005702 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005703 ++ASTContext::NumImplicitMoveAssignmentOperators;
5704
5705 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005706 if (ClassDecl->isDynamicClass() ||
5707 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005708 DeclareImplicitMoveAssignment(ClassDecl);
5709 }
5710
Douglas Gregor4923aa22010-07-02 20:37:36 +00005711 if (!ClassDecl->hasUserDeclaredDestructor()) {
5712 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005713
5714 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005715 // have to declare the destructor immediately. This ensures that, e.g., it
5716 // shows up in the right place in the vtable and that we diagnose problems
5717 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005718 if (ClassDecl->isDynamicClass() ||
5719 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005720 DeclareImplicitDestructor(ClassDecl);
5721 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005722}
5723
Francois Pichet8387e2a2011-04-22 22:18:13 +00005724void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5725 if (!D)
5726 return;
5727
5728 int NumParamList = D->getNumTemplateParameterLists();
5729 for (int i = 0; i < NumParamList; i++) {
5730 TemplateParameterList* Params = D->getTemplateParameterList(i);
5731 for (TemplateParameterList::iterator Param = Params->begin(),
5732 ParamEnd = Params->end();
5733 Param != ParamEnd; ++Param) {
5734 NamedDecl *Named = cast<NamedDecl>(*Param);
5735 if (Named->getDeclName()) {
5736 S->AddDecl(Named);
5737 IdResolver.AddDecl(Named);
5738 }
5739 }
5740 }
5741}
5742
John McCalld226f652010-08-21 09:40:31 +00005743void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005744 if (!D)
5745 return;
5746
5747 TemplateParameterList *Params = 0;
5748 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5749 Params = Template->getTemplateParameters();
5750 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5751 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5752 Params = PartialSpec->getTemplateParameters();
5753 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005754 return;
5755
Douglas Gregor6569d682009-05-27 23:11:45 +00005756 for (TemplateParameterList::iterator Param = Params->begin(),
5757 ParamEnd = Params->end();
5758 Param != ParamEnd; ++Param) {
5759 NamedDecl *Named = cast<NamedDecl>(*Param);
5760 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005761 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005762 IdResolver.AddDecl(Named);
5763 }
5764 }
5765}
5766
John McCalld226f652010-08-21 09:40:31 +00005767void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005768 if (!RecordD) return;
5769 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005770 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005771 PushDeclContext(S, Record);
5772}
5773
John McCalld226f652010-08-21 09:40:31 +00005774void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005775 if (!RecordD) return;
5776 PopDeclContext();
5777}
5778
Douglas Gregor72b505b2008-12-16 21:30:33 +00005779/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5780/// parsing a top-level (non-nested) C++ class, and we are now
5781/// parsing those parts of the given Method declaration that could
5782/// not be parsed earlier (C++ [class.mem]p2), such as default
5783/// arguments. This action should enter the scope of the given
5784/// Method declaration as if we had just parsed the qualified method
5785/// name. However, it should not bring the parameters into scope;
5786/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005787void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005788}
5789
5790/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5791/// C++ method declaration. We're (re-)introducing the given
5792/// function parameter into scope for use in parsing later parts of
5793/// the method declaration. For example, we could see an
5794/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005795void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005796 if (!ParamD)
5797 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005798
John McCalld226f652010-08-21 09:40:31 +00005799 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005800
5801 // If this parameter has an unparsed default argument, clear it out
5802 // to make way for the parsed default argument.
5803 if (Param->hasUnparsedDefaultArg())
5804 Param->setDefaultArg(0);
5805
John McCalld226f652010-08-21 09:40:31 +00005806 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005807 if (Param->getDeclName())
5808 IdResolver.AddDecl(Param);
5809}
5810
5811/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5812/// processing the delayed method declaration for Method. The method
5813/// declaration is now considered finished. There may be a separate
5814/// ActOnStartOfFunctionDef action later (not necessarily
5815/// immediately!) for this method, if it was also defined inside the
5816/// class body.
John McCalld226f652010-08-21 09:40:31 +00005817void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005818 if (!MethodD)
5819 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005820
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005821 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005822
John McCalld226f652010-08-21 09:40:31 +00005823 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005824
5825 // Now that we have our default arguments, check the constructor
5826 // again. It could produce additional diagnostics or affect whether
5827 // the class has implicitly-declared destructors, among other
5828 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005829 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5830 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005831
5832 // Check the default arguments, which we may have added.
5833 if (!Method->isInvalidDecl())
5834 CheckCXXDefaultArguments(Method);
5835}
5836
Douglas Gregor42a552f2008-11-05 20:51:48 +00005837/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005838/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005839/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005840/// emit diagnostics and set the invalid bit to true. In any case, the type
5841/// will be updated to reflect a well-formed type for the constructor and
5842/// returned.
5843QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005844 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005845 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005846
5847 // C++ [class.ctor]p3:
5848 // A constructor shall not be virtual (10.3) or static (9.4). A
5849 // constructor can be invoked for a const, volatile or const
5850 // volatile object. A constructor shall not be declared const,
5851 // volatile, or const volatile (9.3.2).
5852 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005853 if (!D.isInvalidType())
5854 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5855 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5856 << SourceRange(D.getIdentifierLoc());
5857 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005858 }
John McCalld931b082010-08-26 03:08:43 +00005859 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005860 if (!D.isInvalidType())
5861 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5862 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5863 << SourceRange(D.getIdentifierLoc());
5864 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005865 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005866 }
Mike Stump1eb44332009-09-09 15:08:12 +00005867
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005868 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005869 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005870 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005871 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5872 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005873 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005874 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5875 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005876 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005877 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5878 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005879 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005880 }
Mike Stump1eb44332009-09-09 15:08:12 +00005881
Douglas Gregorc938c162011-01-26 05:01:58 +00005882 // C++0x [class.ctor]p4:
5883 // A constructor shall not be declared with a ref-qualifier.
5884 if (FTI.hasRefQualifier()) {
5885 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5886 << FTI.RefQualifierIsLValueRef
5887 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5888 D.setInvalidType();
5889 }
5890
Douglas Gregor42a552f2008-11-05 20:51:48 +00005891 // Rebuild the function type "R" without any type qualifiers (in
5892 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005893 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005894 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005895 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5896 return R;
5897
5898 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5899 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005900 EPI.RefQualifier = RQ_None;
5901
Richard Smith07b0fdc2013-03-18 21:12:30 +00005902 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005903}
5904
Douglas Gregor72b505b2008-12-16 21:30:33 +00005905/// CheckConstructor - Checks a fully-formed constructor for
5906/// well-formedness, issuing any diagnostics required. Returns true if
5907/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005908void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005909 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005910 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5911 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005912 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005913
5914 // C++ [class.copy]p3:
5915 // A declaration of a constructor for a class X is ill-formed if
5916 // its first parameter is of type (optionally cv-qualified) X and
5917 // either there are no other parameters or else all other
5918 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005919 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005920 ((Constructor->getNumParams() == 1) ||
5921 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005922 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5923 Constructor->getTemplateSpecializationKind()
5924 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005925 QualType ParamType = Constructor->getParamDecl(0)->getType();
5926 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5927 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005928 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005929 const char *ConstRef
5930 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5931 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005932 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005933 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005934
5935 // FIXME: Rather that making the constructor invalid, we should endeavor
5936 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005937 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005938 }
5939 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005940}
5941
John McCall15442822010-08-04 01:04:25 +00005942/// CheckDestructor - Checks a fully-formed destructor definition for
5943/// well-formedness, issuing any diagnostics required. Returns true
5944/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005945bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005946 CXXRecordDecl *RD = Destructor->getParent();
5947
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005948 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005949 SourceLocation Loc;
5950
5951 if (!Destructor->isImplicit())
5952 Loc = Destructor->getLocation();
5953 else
5954 Loc = RD->getLocation();
5955
5956 // If we have a virtual destructor, look up the deallocation function
5957 FunctionDecl *OperatorDelete = 0;
5958 DeclarationName Name =
5959 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005960 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005961 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005962
Eli Friedman5f2987c2012-02-02 03:46:19 +00005963 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005964
5965 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005966 }
Anders Carlsson37909802009-11-30 21:24:50 +00005967
5968 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005969}
5970
Mike Stump1eb44332009-09-09 15:08:12 +00005971static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005972FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5973 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5974 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005975 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005976}
5977
Douglas Gregor42a552f2008-11-05 20:51:48 +00005978/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5979/// the well-formednes of the destructor declarator @p D with type @p
5980/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005981/// emit diagnostics and set the declarator to invalid. Even if this happens,
5982/// will be updated to reflect a well-formed type for the destructor and
5983/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005984QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005985 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005986 // C++ [class.dtor]p1:
5987 // [...] A typedef-name that names a class is a class-name
5988 // (7.1.3); however, a typedef-name that names a class shall not
5989 // be used as the identifier in the declarator for a destructor
5990 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005991 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005992 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005993 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005994 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005995 else if (const TemplateSpecializationType *TST =
5996 DeclaratorType->getAs<TemplateSpecializationType>())
5997 if (TST->isTypeAlias())
5998 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5999 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006000
6001 // C++ [class.dtor]p2:
6002 // A destructor is used to destroy objects of its class type. A
6003 // destructor takes no parameters, and no return type can be
6004 // specified for it (not even void). The address of a destructor
6005 // shall not be taken. A destructor shall not be static. A
6006 // destructor can be invoked for a const, volatile or const
6007 // volatile object. A destructor shall not be declared const,
6008 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006009 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006010 if (!D.isInvalidType())
6011 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6012 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006013 << SourceRange(D.getIdentifierLoc())
6014 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6015
John McCalld931b082010-08-26 03:08:43 +00006016 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006017 }
Chris Lattner65401802009-04-25 08:28:21 +00006018 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006019 // Destructors don't have return types, but the parser will
6020 // happily parse something like:
6021 //
6022 // class X {
6023 // float ~X();
6024 // };
6025 //
6026 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006027 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6028 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6029 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006030 }
Mike Stump1eb44332009-09-09 15:08:12 +00006031
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006032 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006033 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006034 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006035 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6036 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006037 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006038 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6039 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006040 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006041 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6042 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006043 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006044 }
6045
Douglas Gregorc938c162011-01-26 05:01:58 +00006046 // C++0x [class.dtor]p2:
6047 // A destructor shall not be declared with a ref-qualifier.
6048 if (FTI.hasRefQualifier()) {
6049 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6050 << FTI.RefQualifierIsLValueRef
6051 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6052 D.setInvalidType();
6053 }
6054
Douglas Gregor42a552f2008-11-05 20:51:48 +00006055 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006056 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006057 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6058
6059 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006060 FTI.freeArgs();
6061 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006062 }
6063
Mike Stump1eb44332009-09-09 15:08:12 +00006064 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006065 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006066 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006067 D.setInvalidType();
6068 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006069
6070 // Rebuild the function type "R" without any type qualifiers or
6071 // parameters (in case any of the errors above fired) and with
6072 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006073 // types.
John McCalle23cf432010-12-14 08:05:40 +00006074 if (!D.isInvalidType())
6075 return R;
6076
Douglas Gregord92ec472010-07-01 05:10:53 +00006077 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006078 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6079 EPI.Variadic = false;
6080 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006081 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006082 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006083}
6084
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006085/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6086/// well-formednes of the conversion function declarator @p D with
6087/// type @p R. If there are any errors in the declarator, this routine
6088/// will emit diagnostics and return true. Otherwise, it will return
6089/// false. Either way, the type @p R will be updated to reflect a
6090/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006091void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006092 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006093 // C++ [class.conv.fct]p1:
6094 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006095 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006096 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006097 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006098 if (!D.isInvalidType())
6099 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006100 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6101 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006102 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006103 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006104 }
John McCalla3f81372010-04-13 00:04:31 +00006105
6106 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6107
Chris Lattner6e475012009-04-25 08:35:12 +00006108 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006109 // Conversion functions don't have return types, but the parser will
6110 // happily parse something like:
6111 //
6112 // class X {
6113 // float operator bool();
6114 // };
6115 //
6116 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006117 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6118 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6119 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006120 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006121 }
6122
John McCalla3f81372010-04-13 00:04:31 +00006123 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6124
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006125 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006126 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006127 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6128
6129 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006130 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006131 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006132 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006133 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006134 D.setInvalidType();
6135 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006136
John McCalla3f81372010-04-13 00:04:31 +00006137 // Diagnose "&operator bool()" and other such nonsense. This
6138 // is actually a gcc extension which we don't support.
6139 if (Proto->getResultType() != ConvType) {
6140 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6141 << Proto->getResultType();
6142 D.setInvalidType();
6143 ConvType = Proto->getResultType();
6144 }
6145
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006146 // C++ [class.conv.fct]p4:
6147 // The conversion-type-id shall not represent a function type nor
6148 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006149 if (ConvType->isArrayType()) {
6150 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6151 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006152 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006153 } else if (ConvType->isFunctionType()) {
6154 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6155 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006156 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006157 }
6158
6159 // Rebuild the function type "R" without any parameters (in case any
6160 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006161 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006162 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006163 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006164
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006165 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006166 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006167 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006168 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006169 diag::warn_cxx98_compat_explicit_conversion_functions :
6170 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006171 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006172}
6173
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006174/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6175/// the declaration of the given C++ conversion function. This routine
6176/// is responsible for recording the conversion function in the C++
6177/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006178Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006179 assert(Conversion && "Expected to receive a conversion function declaration");
6180
Douglas Gregor9d350972008-12-12 08:25:50 +00006181 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006182
6183 // Make sure we aren't redeclaring the conversion function.
6184 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006185
6186 // C++ [class.conv.fct]p1:
6187 // [...] A conversion function is never used to convert a
6188 // (possibly cv-qualified) object to the (possibly cv-qualified)
6189 // same object type (or a reference to it), to a (possibly
6190 // cv-qualified) base class of that type (or a reference to it),
6191 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006192 // FIXME: Suppress this warning if the conversion function ends up being a
6193 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006194 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006195 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006196 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006197 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006198 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6199 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006200 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006201 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006202 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6203 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006204 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006205 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006206 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006207 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006208 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006209 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006210 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006211 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006212 }
6213
Douglas Gregore80622f2010-09-29 04:25:11 +00006214 if (FunctionTemplateDecl *ConversionTemplate
6215 = Conversion->getDescribedFunctionTemplate())
6216 return ConversionTemplate;
6217
John McCalld226f652010-08-21 09:40:31 +00006218 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006219}
6220
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006221//===----------------------------------------------------------------------===//
6222// Namespace Handling
6223//===----------------------------------------------------------------------===//
6224
Richard Smithd1a55a62012-10-04 22:13:39 +00006225/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6226/// reopened.
6227static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6228 SourceLocation Loc,
6229 IdentifierInfo *II, bool *IsInline,
6230 NamespaceDecl *PrevNS) {
6231 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006232
Richard Smithc969e6a2012-10-05 01:46:25 +00006233 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6234 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6235 // inline namespaces, with the intention of bringing names into namespace std.
6236 //
6237 // We support this just well enough to get that case working; this is not
6238 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006239 if (*IsInline && II && II->getName().startswith("__atomic") &&
6240 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006241 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006242 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6243 NS = NS->getPreviousDecl())
6244 NS->setInline(*IsInline);
6245 // Patch up the lookup table for the containing namespace. This isn't really
6246 // correct, but it's good enough for this particular case.
6247 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6248 E = PrevNS->decls_end(); I != E; ++I)
6249 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6250 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6251 return;
6252 }
6253
6254 if (PrevNS->isInline())
6255 // The user probably just forgot the 'inline', so suggest that it
6256 // be added back.
6257 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6258 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6259 else
6260 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6261 << IsInline;
6262
6263 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6264 *IsInline = PrevNS->isInline();
6265}
John McCallea318642010-08-26 09:15:37 +00006266
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006267/// ActOnStartNamespaceDef - This is called at the start of a namespace
6268/// definition.
John McCalld226f652010-08-21 09:40:31 +00006269Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006270 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006271 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006272 SourceLocation IdentLoc,
6273 IdentifierInfo *II,
6274 SourceLocation LBrace,
6275 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006276 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6277 // For anonymous namespace, take the location of the left brace.
6278 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006279 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006280 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006281 bool IsStd = false;
6282 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006283 Scope *DeclRegionScope = NamespcScope->getParent();
6284
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006285 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006286 if (II) {
6287 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006288 // The identifier in an original-namespace-definition shall not
6289 // have been previously defined in the declarative region in
6290 // which the original-namespace-definition appears. The
6291 // identifier in an original-namespace-definition is the name of
6292 // the namespace. Subsequently in that declarative region, it is
6293 // treated as an original-namespace-name.
6294 //
6295 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006296 // look through using directives, just look for any ordinary names.
6297
6298 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006299 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6300 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006301 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006302 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6303 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6304 ++I) {
6305 if ((*I)->getIdentifierNamespace() & IDNS) {
6306 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006307 break;
6308 }
6309 }
6310
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006311 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6312
6313 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006314 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006315 if (IsInline != PrevNS->isInline())
6316 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6317 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006318 } else if (PrevDecl) {
6319 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006320 Diag(Loc, diag::err_redefinition_different_kind)
6321 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006322 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006323 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006324 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006325 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006326 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006327 // This is the first "real" definition of the namespace "std", so update
6328 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006329 PrevNS = getStdNamespace();
6330 IsStd = true;
6331 AddToKnown = !IsInline;
6332 } else {
6333 // We've seen this namespace for the first time.
6334 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006335 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006336 } else {
John McCall9aeed322009-10-01 00:25:31 +00006337 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006338
6339 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006340 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006341 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006342 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006343 } else {
6344 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006345 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006346 }
6347
Richard Smithd1a55a62012-10-04 22:13:39 +00006348 if (PrevNS && IsInline != PrevNS->isInline())
6349 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6350 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006351 }
6352
6353 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6354 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006355 if (IsInvalid)
6356 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006357
6358 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006359
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006360 // FIXME: Should we be merging attributes?
6361 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006362 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006363
6364 if (IsStd)
6365 StdNamespace = Namespc;
6366 if (AddToKnown)
6367 KnownNamespaces[Namespc] = false;
6368
6369 if (II) {
6370 PushOnScopeChains(Namespc, DeclRegionScope);
6371 } else {
6372 // Link the anonymous namespace into its parent.
6373 DeclContext *Parent = CurContext->getRedeclContext();
6374 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6375 TU->setAnonymousNamespace(Namespc);
6376 } else {
6377 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006378 }
John McCall9aeed322009-10-01 00:25:31 +00006379
Douglas Gregora4181472010-03-24 00:46:35 +00006380 CurContext->addDecl(Namespc);
6381
John McCall9aeed322009-10-01 00:25:31 +00006382 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6383 // behaves as if it were replaced by
6384 // namespace unique { /* empty body */ }
6385 // using namespace unique;
6386 // namespace unique { namespace-body }
6387 // where all occurrences of 'unique' in a translation unit are
6388 // replaced by the same identifier and this identifier differs
6389 // from all other identifiers in the entire program.
6390
6391 // We just create the namespace with an empty name and then add an
6392 // implicit using declaration, just like the standard suggests.
6393 //
6394 // CodeGen enforces the "universally unique" aspect by giving all
6395 // declarations semantically contained within an anonymous
6396 // namespace internal linkage.
6397
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006398 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006399 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006400 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006401 /* 'using' */ LBrace,
6402 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006403 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006404 /* identifier */ SourceLocation(),
6405 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006406 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006407 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006408 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006409 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006410 }
6411
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006412 ActOnDocumentableDecl(Namespc);
6413
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006414 // Although we could have an invalid decl (i.e. the namespace name is a
6415 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006416 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6417 // for the namespace has the declarations that showed up in that particular
6418 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006419 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006420 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006421}
6422
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006423/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6424/// is a namespace alias, returns the namespace it points to.
6425static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6426 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6427 return AD->getNamespace();
6428 return dyn_cast_or_null<NamespaceDecl>(D);
6429}
6430
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006431/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6432/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006433void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006434 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6435 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006436 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006437 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006438 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006439 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006440}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006441
John McCall384aff82010-08-25 07:42:41 +00006442CXXRecordDecl *Sema::getStdBadAlloc() const {
6443 return cast_or_null<CXXRecordDecl>(
6444 StdBadAlloc.get(Context.getExternalSource()));
6445}
6446
6447NamespaceDecl *Sema::getStdNamespace() const {
6448 return cast_or_null<NamespaceDecl>(
6449 StdNamespace.get(Context.getExternalSource()));
6450}
6451
Douglas Gregor66992202010-06-29 17:53:46 +00006452/// \brief Retrieve the special "std" namespace, which may require us to
6453/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006454NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006455 if (!StdNamespace) {
6456 // The "std" namespace has not yet been defined, so build one implicitly.
6457 StdNamespace = NamespaceDecl::Create(Context,
6458 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006459 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006460 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006461 &PP.getIdentifierTable().get("std"),
6462 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006463 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006464 }
6465
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006466 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006467}
6468
Sebastian Redl395e04d2012-01-17 22:49:33 +00006469bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006470 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006471 "Looking for std::initializer_list outside of C++.");
6472
6473 // We're looking for implicit instantiations of
6474 // template <typename E> class std::initializer_list.
6475
6476 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6477 return false;
6478
Sebastian Redl84760e32012-01-17 22:49:58 +00006479 ClassTemplateDecl *Template = 0;
6480 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006481
Sebastian Redl84760e32012-01-17 22:49:58 +00006482 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006483
Sebastian Redl84760e32012-01-17 22:49:58 +00006484 ClassTemplateSpecializationDecl *Specialization =
6485 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6486 if (!Specialization)
6487 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006488
Sebastian Redl84760e32012-01-17 22:49:58 +00006489 Template = Specialization->getSpecializedTemplate();
6490 Arguments = Specialization->getTemplateArgs().data();
6491 } else if (const TemplateSpecializationType *TST =
6492 Ty->getAs<TemplateSpecializationType>()) {
6493 Template = dyn_cast_or_null<ClassTemplateDecl>(
6494 TST->getTemplateName().getAsTemplateDecl());
6495 Arguments = TST->getArgs();
6496 }
6497 if (!Template)
6498 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006499
6500 if (!StdInitializerList) {
6501 // Haven't recognized std::initializer_list yet, maybe this is it.
6502 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6503 if (TemplateClass->getIdentifier() !=
6504 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006505 !getStdNamespace()->InEnclosingNamespaceSetOf(
6506 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006507 return false;
6508 // This is a template called std::initializer_list, but is it the right
6509 // template?
6510 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006511 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006512 return false;
6513 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6514 return false;
6515
6516 // It's the right template.
6517 StdInitializerList = Template;
6518 }
6519
6520 if (Template != StdInitializerList)
6521 return false;
6522
6523 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006524 if (Element)
6525 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006526 return true;
6527}
6528
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006529static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6530 NamespaceDecl *Std = S.getStdNamespace();
6531 if (!Std) {
6532 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6533 return 0;
6534 }
6535
6536 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6537 Loc, Sema::LookupOrdinaryName);
6538 if (!S.LookupQualifiedName(Result, Std)) {
6539 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6540 return 0;
6541 }
6542 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6543 if (!Template) {
6544 Result.suppressDiagnostics();
6545 // We found something weird. Complain about the first thing we found.
6546 NamedDecl *Found = *Result.begin();
6547 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6548 return 0;
6549 }
6550
6551 // We found some template called std::initializer_list. Now verify that it's
6552 // correct.
6553 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006554 if (Params->getMinRequiredArguments() != 1 ||
6555 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006556 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6557 return 0;
6558 }
6559
6560 return Template;
6561}
6562
6563QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6564 if (!StdInitializerList) {
6565 StdInitializerList = LookupStdInitializerList(*this, Loc);
6566 if (!StdInitializerList)
6567 return QualType();
6568 }
6569
6570 TemplateArgumentListInfo Args(Loc, Loc);
6571 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6572 Context.getTrivialTypeSourceInfo(Element,
6573 Loc)));
6574 return Context.getCanonicalType(
6575 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6576}
6577
Sebastian Redl98d36062012-01-17 22:50:14 +00006578bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6579 // C++ [dcl.init.list]p2:
6580 // A constructor is an initializer-list constructor if its first parameter
6581 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6582 // std::initializer_list<E> for some type E, and either there are no other
6583 // parameters or else all other parameters have default arguments.
6584 if (Ctor->getNumParams() < 1 ||
6585 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6586 return false;
6587
6588 QualType ArgType = Ctor->getParamDecl(0)->getType();
6589 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6590 ArgType = RT->getPointeeType().getUnqualifiedType();
6591
6592 return isStdInitializerList(ArgType, 0);
6593}
6594
Douglas Gregor9172aa62011-03-26 22:25:30 +00006595/// \brief Determine whether a using statement is in a context where it will be
6596/// apply in all contexts.
6597static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6598 switch (CurContext->getDeclKind()) {
6599 case Decl::TranslationUnit:
6600 return true;
6601 case Decl::LinkageSpec:
6602 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6603 default:
6604 return false;
6605 }
6606}
6607
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006608namespace {
6609
6610// Callback to only accept typo corrections that are namespaces.
6611class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6612 public:
6613 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6614 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6615 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6616 }
6617 return false;
6618 }
6619};
6620
6621}
6622
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006623static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6624 CXXScopeSpec &SS,
6625 SourceLocation IdentLoc,
6626 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006627 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006628 R.clear();
6629 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006630 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006631 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006632 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6633 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006634 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6635 bool droppedSpecifier = Corrected.WillReplaceSpecifier() &&
6636 Ident->getName().equals(CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006637 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006638 << Ident << DC << droppedSpecifier << CorrectedQuotedStr
6639 << SS.getRange() << FixItHint::CreateReplacement(
6640 Corrected.getCorrectionRange(), CorrectedStr);
6641 } else {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006642 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6643 << Ident << CorrectedQuotedStr
6644 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006645 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006646
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006647 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6648 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006649
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006650 R.addDecl(Corrected.getCorrectionDecl());
6651 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006652 }
6653 return false;
6654}
6655
John McCalld226f652010-08-21 09:40:31 +00006656Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006657 SourceLocation UsingLoc,
6658 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006659 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006660 SourceLocation IdentLoc,
6661 IdentifierInfo *NamespcName,
6662 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006663 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6664 assert(NamespcName && "Invalid NamespcName.");
6665 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006666
6667 // This can only happen along a recovery path.
6668 while (S->getFlags() & Scope::TemplateParamScope)
6669 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006670 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006671
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006672 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006673 NestedNameSpecifier *Qualifier = 0;
6674 if (SS.isSet())
6675 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6676
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006677 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006678 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6679 LookupParsedName(R, S, &SS);
6680 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006681 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006682
Douglas Gregor66992202010-06-29 17:53:46 +00006683 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006684 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006685 // Allow "using namespace std;" or "using namespace ::std;" even if
6686 // "std" hasn't been defined yet, for GCC compatibility.
6687 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6688 NamespcName->isStr("std")) {
6689 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006690 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006691 R.resolveKind();
6692 }
6693 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006694 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006695 }
6696
John McCallf36e02d2009-10-09 21:13:30 +00006697 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006698 NamedDecl *Named = R.getFoundDecl();
6699 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6700 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006701 // C++ [namespace.udir]p1:
6702 // A using-directive specifies that the names in the nominated
6703 // namespace can be used in the scope in which the
6704 // using-directive appears after the using-directive. During
6705 // unqualified name lookup (3.4.1), the names appear as if they
6706 // were declared in the nearest enclosing namespace which
6707 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006708 // namespace. [Note: in this context, "contains" means "contains
6709 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006710
6711 // Find enclosing context containing both using-directive and
6712 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006713 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006714 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6715 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6716 CommonAncestor = CommonAncestor->getParent();
6717
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006718 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006719 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006720 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006721
Douglas Gregor9172aa62011-03-26 22:25:30 +00006722 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006723 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006724 Diag(IdentLoc, diag::warn_using_directive_in_header);
6725 }
6726
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006727 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006728 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006729 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006730 }
6731
Richard Smith6b3d3e52013-02-20 19:22:51 +00006732 if (UDir)
6733 ProcessDeclAttributeList(S, UDir, AttrList);
6734
John McCalld226f652010-08-21 09:40:31 +00006735 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006736}
6737
6738void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006739 // If the scope has an associated entity and the using directive is at
6740 // namespace or translation unit scope, add the UsingDirectiveDecl into
6741 // its lookup structure so qualified name lookup can find it.
6742 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6743 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006744 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006745 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006746 // Otherwise, it is at block sope. The using-directives will affect lookup
6747 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006748 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006749}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006750
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006751
John McCalld226f652010-08-21 09:40:31 +00006752Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006753 AccessSpecifier AS,
6754 bool HasUsingKeyword,
6755 SourceLocation UsingLoc,
6756 CXXScopeSpec &SS,
6757 UnqualifiedId &Name,
6758 AttributeList *AttrList,
6759 bool IsTypeName,
6760 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006761 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006762
Douglas Gregor12c118a2009-11-04 16:30:06 +00006763 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006764 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006765 case UnqualifiedId::IK_Identifier:
6766 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006767 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006768 case UnqualifiedId::IK_ConversionFunctionId:
6769 break;
6770
6771 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006772 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006773 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006774 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006775 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006776 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006777 diag::err_using_decl_constructor)
6778 << SS.getRange();
6779
Richard Smith80ad52f2013-01-02 11:42:31 +00006780 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006781
John McCalld226f652010-08-21 09:40:31 +00006782 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006783
6784 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006785 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006786 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006787 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006788
6789 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006790 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006791 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006792 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006793 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006794
6795 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6796 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006797 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006798 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006799
Richard Smith07b0fdc2013-03-18 21:12:30 +00006800 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006801 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006802 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006803 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6804 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006805 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006806 }
6807
Douglas Gregor56c04582010-12-16 00:46:58 +00006808 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6809 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6810 return 0;
6811
John McCall9488ea12009-11-17 05:59:44 +00006812 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006813 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006814 /* IsInstantiation */ false,
6815 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006816 if (UD)
6817 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006818
John McCalld226f652010-08-21 09:40:31 +00006819 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006820}
6821
Douglas Gregor09acc982010-07-07 23:08:52 +00006822/// \brief Determine whether a using declaration considers the given
6823/// declarations as "equivalent", e.g., if they are redeclarations of
6824/// the same entity or are both typedefs of the same type.
6825static bool
6826IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6827 bool &SuppressRedeclaration) {
6828 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6829 SuppressRedeclaration = false;
6830 return true;
6831 }
6832
Richard Smith162e1c12011-04-15 14:24:37 +00006833 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6834 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006835 SuppressRedeclaration = true;
6836 return Context.hasSameType(TD1->getUnderlyingType(),
6837 TD2->getUnderlyingType());
6838 }
6839
6840 return false;
6841}
6842
6843
John McCall9f54ad42009-12-10 09:41:52 +00006844/// Determines whether to create a using shadow decl for a particular
6845/// decl, given the set of decls existing prior to this using lookup.
6846bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6847 const LookupResult &Previous) {
6848 // Diagnose finding a decl which is not from a base class of the
6849 // current class. We do this now because there are cases where this
6850 // function will silently decide not to build a shadow decl, which
6851 // will pre-empt further diagnostics.
6852 //
6853 // We don't need to do this in C++0x because we do the check once on
6854 // the qualifier.
6855 //
6856 // FIXME: diagnose the following if we care enough:
6857 // struct A { int foo; };
6858 // struct B : A { using A::foo; };
6859 // template <class T> struct C : A {};
6860 // template <class T> struct D : C<T> { using B::foo; } // <---
6861 // This is invalid (during instantiation) in C++03 because B::foo
6862 // resolves to the using decl in B, which is not a base class of D<T>.
6863 // We can't diagnose it immediately because C<T> is an unknown
6864 // specialization. The UsingShadowDecl in D<T> then points directly
6865 // to A::foo, which will look well-formed when we instantiate.
6866 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006867 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006868 DeclContext *OrigDC = Orig->getDeclContext();
6869
6870 // Handle enums and anonymous structs.
6871 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6872 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6873 while (OrigRec->isAnonymousStructOrUnion())
6874 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6875
6876 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6877 if (OrigDC == CurContext) {
6878 Diag(Using->getLocation(),
6879 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006880 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006881 Diag(Orig->getLocation(), diag::note_using_decl_target);
6882 return true;
6883 }
6884
Douglas Gregordc355712011-02-25 00:36:19 +00006885 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006886 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006887 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006888 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006889 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006890 Diag(Orig->getLocation(), diag::note_using_decl_target);
6891 return true;
6892 }
6893 }
6894
6895 if (Previous.empty()) return false;
6896
6897 NamedDecl *Target = Orig;
6898 if (isa<UsingShadowDecl>(Target))
6899 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6900
John McCalld7533ec2009-12-11 02:33:26 +00006901 // If the target happens to be one of the previous declarations, we
6902 // don't have a conflict.
6903 //
6904 // FIXME: but we might be increasing its access, in which case we
6905 // should redeclare it.
6906 NamedDecl *NonTag = 0, *Tag = 0;
6907 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6908 I != E; ++I) {
6909 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006910 bool Result;
6911 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6912 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006913
6914 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6915 }
6916
John McCall9f54ad42009-12-10 09:41:52 +00006917 if (Target->isFunctionOrFunctionTemplate()) {
6918 FunctionDecl *FD;
6919 if (isa<FunctionTemplateDecl>(Target))
6920 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6921 else
6922 FD = cast<FunctionDecl>(Target);
6923
6924 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006925 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006926 case Ovl_Overload:
6927 return false;
6928
6929 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006930 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006931 break;
6932
6933 // We found a decl with the exact signature.
6934 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006935 // If we're in a record, we want to hide the target, so we
6936 // return true (without a diagnostic) to tell the caller not to
6937 // build a shadow decl.
6938 if (CurContext->isRecord())
6939 return true;
6940
6941 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006942 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006943 break;
6944 }
6945
6946 Diag(Target->getLocation(), diag::note_using_decl_target);
6947 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6948 return true;
6949 }
6950
6951 // Target is not a function.
6952
John McCall9f54ad42009-12-10 09:41:52 +00006953 if (isa<TagDecl>(Target)) {
6954 // No conflict between a tag and a non-tag.
6955 if (!Tag) return false;
6956
John McCall41ce66f2009-12-10 19:51:03 +00006957 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006958 Diag(Target->getLocation(), diag::note_using_decl_target);
6959 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6960 return true;
6961 }
6962
6963 // No conflict between a tag and a non-tag.
6964 if (!NonTag) return false;
6965
John McCall41ce66f2009-12-10 19:51:03 +00006966 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006967 Diag(Target->getLocation(), diag::note_using_decl_target);
6968 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6969 return true;
6970}
6971
John McCall9488ea12009-11-17 05:59:44 +00006972/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006973UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006974 UsingDecl *UD,
6975 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006976
6977 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006978 NamedDecl *Target = Orig;
6979 if (isa<UsingShadowDecl>(Target)) {
6980 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6981 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006982 }
6983
6984 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006985 = UsingShadowDecl::Create(Context, CurContext,
6986 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006987 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006988
6989 Shadow->setAccess(UD->getAccess());
6990 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6991 Shadow->setInvalidDecl();
6992
John McCall9488ea12009-11-17 05:59:44 +00006993 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006994 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006995 else
John McCall604e7f12009-12-08 07:46:18 +00006996 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006997
John McCall604e7f12009-12-08 07:46:18 +00006998
John McCall9f54ad42009-12-10 09:41:52 +00006999 return Shadow;
7000}
John McCall604e7f12009-12-08 07:46:18 +00007001
John McCall9f54ad42009-12-10 09:41:52 +00007002/// Hides a using shadow declaration. This is required by the current
7003/// using-decl implementation when a resolvable using declaration in a
7004/// class is followed by a declaration which would hide or override
7005/// one or more of the using decl's targets; for example:
7006///
7007/// struct Base { void foo(int); };
7008/// struct Derived : Base {
7009/// using Base::foo;
7010/// void foo(int);
7011/// };
7012///
7013/// The governing language is C++03 [namespace.udecl]p12:
7014///
7015/// When a using-declaration brings names from a base class into a
7016/// derived class scope, member functions in the derived class
7017/// override and/or hide member functions with the same name and
7018/// parameter types in a base class (rather than conflicting).
7019///
7020/// There are two ways to implement this:
7021/// (1) optimistically create shadow decls when they're not hidden
7022/// by existing declarations, or
7023/// (2) don't create any shadow decls (or at least don't make them
7024/// visible) until we've fully parsed/instantiated the class.
7025/// The problem with (1) is that we might have to retroactively remove
7026/// a shadow decl, which requires several O(n) operations because the
7027/// decl structures are (very reasonably) not designed for removal.
7028/// (2) avoids this but is very fiddly and phase-dependent.
7029void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007030 if (Shadow->getDeclName().getNameKind() ==
7031 DeclarationName::CXXConversionFunctionName)
7032 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7033
John McCall9f54ad42009-12-10 09:41:52 +00007034 // Remove it from the DeclContext...
7035 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007036
John McCall9f54ad42009-12-10 09:41:52 +00007037 // ...and the scope, if applicable...
7038 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007039 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007040 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007041 }
7042
John McCall9f54ad42009-12-10 09:41:52 +00007043 // ...and the using decl.
7044 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7045
7046 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007047 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007048}
7049
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007050class UsingValidatorCCC : public CorrectionCandidateCallback {
7051public:
7052 UsingValidatorCCC(bool IsTypeName, bool IsInstantiation)
7053 : IsTypeName(IsTypeName), IsInstantiation(IsInstantiation) {}
7054
7055 virtual bool ValidateCandidate(const TypoCorrection &Candidate) {
7056 if (NamedDecl *ND = Candidate.getCorrectionDecl()) {
7057 if (isa<NamespaceDecl>(ND))
7058 return false;
7059 // Completely unqualified names are invalid for a 'using' declaration.
7060 bool droppedSpecifier = Candidate.WillReplaceSpecifier() &&
7061 !Candidate.getCorrectionSpecifier();
7062 if (droppedSpecifier)
7063 return false;
7064 else if (isa<TypeDecl>(ND))
7065 return IsTypeName || !IsInstantiation;
7066 else
7067 return !IsTypeName;
7068 } else {
7069 // Keywords are not valid here.
7070 return false;
7071 }
7072 }
7073
7074private:
7075 bool IsTypeName;
7076 bool IsInstantiation;
7077};
7078
John McCall7ba107a2009-11-18 02:36:19 +00007079/// Builds a using declaration.
7080///
7081/// \param IsInstantiation - Whether this call arises from an
7082/// instantiation of an unresolved using declaration. We treat
7083/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007084NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7085 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007086 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007087 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007088 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007089 bool IsInstantiation,
7090 bool IsTypeName,
7091 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007092 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007093 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007094 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007095
Anders Carlsson550b14b2009-08-28 05:49:21 +00007096 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007097
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007098 if (SS.isEmpty()) {
7099 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007100 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007101 }
Mike Stump1eb44332009-09-09 15:08:12 +00007102
John McCall9f54ad42009-12-10 09:41:52 +00007103 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007104 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007105 ForRedeclaration);
7106 Previous.setHideTags(false);
7107 if (S) {
7108 LookupName(Previous, S);
7109
7110 // It is really dumb that we have to do this.
7111 LookupResult::Filter F = Previous.makeFilter();
7112 while (F.hasNext()) {
7113 NamedDecl *D = F.next();
7114 if (!isDeclInScope(D, CurContext, S))
7115 F.erase();
7116 }
7117 F.done();
7118 } else {
7119 assert(IsInstantiation && "no scope in non-instantiation");
7120 assert(CurContext->isRecord() && "scope not record in instantiation");
7121 LookupQualifiedName(Previous, CurContext);
7122 }
7123
John McCall9f54ad42009-12-10 09:41:52 +00007124 // Check for invalid redeclarations.
7125 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7126 return 0;
7127
7128 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007129 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7130 return 0;
7131
John McCallaf8e6ed2009-11-12 03:15:40 +00007132 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007133 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007134 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007135 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007136 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007137 // FIXME: not all declaration name kinds are legal here
7138 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7139 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007140 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007141 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007142 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007143 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7144 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007145 }
John McCalled976492009-12-04 22:46:56 +00007146 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007147 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7148 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007149 }
John McCalled976492009-12-04 22:46:56 +00007150 D->setAccess(AS);
7151 CurContext->addDecl(D);
7152
7153 if (!LookupContext) return D;
7154 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007155
John McCall77bb1aa2010-05-01 00:40:08 +00007156 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007157 UD->setInvalidDecl();
7158 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007159 }
7160
Richard Smithc5a89a12012-04-02 01:30:27 +00007161 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007162 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007163 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007164 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007165 return UD;
7166 }
7167
7168 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007169
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007170 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007171
John McCall604e7f12009-12-08 07:46:18 +00007172 // Unlike most lookups, we don't always want to hide tag
7173 // declarations: tag names are visible through the using declaration
7174 // even if hidden by ordinary names, *except* in a dependent context
7175 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007176 if (!IsInstantiation)
7177 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007178
John McCallb9abd8722012-04-07 03:04:20 +00007179 // For the purposes of this lookup, we have a base object type
7180 // equal to that of the current context.
7181 if (CurContext->isRecord()) {
7182 R.setBaseObjectType(
7183 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7184 }
7185
John McCalla24dc2e2009-11-17 02:14:36 +00007186 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007187
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007188 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007189 if (R.empty()) {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007190 UsingValidatorCCC CCC(IsTypeName, IsInstantiation);
7191 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7192 R.getLookupKind(), S, &SS, CCC)){
7193 // We reject any correction for which ND would be NULL.
7194 NamedDecl *ND = Corrected.getCorrectionDecl();
7195 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
7196 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
7197 R.setLookupName(Corrected.getCorrection());
7198 R.addDecl(ND);
7199 // We reject candidates where droppedSpecifier == true, hence the
7200 // literal '0' below.
7201 Diag(R.getNameLoc(), diag::err_no_member_suggest)
7202 << NameInfo.getName() << LookupContext << 0
7203 << CorrectedQuotedStr << SS.getRange()
7204 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
7205 CorrectedStr);
7206 Diag(ND->getLocation(), diag::note_previous_decl)
7207 << CorrectedQuotedStr;
7208 } else {
7209 Diag(IdentLoc, diag::err_no_member)
7210 << NameInfo.getName() << LookupContext << SS.getRange();
7211 UD->setInvalidDecl();
7212 return UD;
7213 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007214 }
7215
John McCalled976492009-12-04 22:46:56 +00007216 if (R.isAmbiguous()) {
7217 UD->setInvalidDecl();
7218 return UD;
7219 }
Mike Stump1eb44332009-09-09 15:08:12 +00007220
John McCall7ba107a2009-11-18 02:36:19 +00007221 if (IsTypeName) {
7222 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007223 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007224 Diag(IdentLoc, diag::err_using_typename_non_type);
7225 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7226 Diag((*I)->getUnderlyingDecl()->getLocation(),
7227 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007228 UD->setInvalidDecl();
7229 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007230 }
7231 } else {
7232 // If we asked for a non-typename and we got a type, error out,
7233 // but only if this is an instantiation of an unresolved using
7234 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007235 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007236 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7237 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007238 UD->setInvalidDecl();
7239 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007240 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007241 }
7242
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007243 // C++0x N2914 [namespace.udecl]p6:
7244 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007245 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007246 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7247 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007248 UD->setInvalidDecl();
7249 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007250 }
Mike Stump1eb44332009-09-09 15:08:12 +00007251
John McCall9f54ad42009-12-10 09:41:52 +00007252 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7253 if (!CheckUsingShadowDecl(UD, *I, Previous))
7254 BuildUsingShadowDecl(S, UD, *I);
7255 }
John McCall9488ea12009-11-17 05:59:44 +00007256
7257 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007258}
7259
Sebastian Redlf677ea32011-02-05 19:23:19 +00007260/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007261bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7262 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007263
Douglas Gregordc355712011-02-25 00:36:19 +00007264 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007265 assert(SourceType &&
7266 "Using decl naming constructor doesn't have type in scope spec.");
7267 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7268
7269 // Check whether the named type is a direct base class.
7270 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7271 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7272 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7273 BaseIt != BaseE; ++BaseIt) {
7274 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7275 if (CanonicalSourceType == BaseType)
7276 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007277 if (BaseIt->getType()->isDependentType())
7278 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007279 }
7280
7281 if (BaseIt == BaseE) {
7282 // Did not find SourceType in the bases.
7283 Diag(UD->getUsingLocation(),
7284 diag::err_using_decl_constructor_not_in_direct_base)
7285 << UD->getNameInfo().getSourceRange()
7286 << QualType(SourceType, 0) << TargetClass;
7287 return true;
7288 }
7289
Richard Smithc5a89a12012-04-02 01:30:27 +00007290 if (!CurContext->isDependentContext())
7291 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007292
7293 return false;
7294}
7295
John McCall9f54ad42009-12-10 09:41:52 +00007296/// Checks that the given using declaration is not an invalid
7297/// redeclaration. Note that this is checking only for the using decl
7298/// itself, not for any ill-formedness among the UsingShadowDecls.
7299bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7300 bool isTypeName,
7301 const CXXScopeSpec &SS,
7302 SourceLocation NameLoc,
7303 const LookupResult &Prev) {
7304 // C++03 [namespace.udecl]p8:
7305 // C++0x [namespace.udecl]p10:
7306 // A using-declaration is a declaration and can therefore be used
7307 // repeatedly where (and only where) multiple declarations are
7308 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007309 //
John McCall8a726212010-11-29 18:01:58 +00007310 // That's in non-member contexts.
7311 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007312 return false;
7313
7314 NestedNameSpecifier *Qual
7315 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7316
7317 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7318 NamedDecl *D = *I;
7319
7320 bool DTypename;
7321 NestedNameSpecifier *DQual;
7322 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7323 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007324 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007325 } else if (UnresolvedUsingValueDecl *UD
7326 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7327 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007328 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007329 } else if (UnresolvedUsingTypenameDecl *UD
7330 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7331 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007332 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007333 } else continue;
7334
7335 // using decls differ if one says 'typename' and the other doesn't.
7336 // FIXME: non-dependent using decls?
7337 if (isTypeName != DTypename) continue;
7338
7339 // using decls differ if they name different scopes (but note that
7340 // template instantiation can cause this check to trigger when it
7341 // didn't before instantiation).
7342 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7343 Context.getCanonicalNestedNameSpecifier(DQual))
7344 continue;
7345
7346 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007347 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007348 return true;
7349 }
7350
7351 return false;
7352}
7353
John McCall604e7f12009-12-08 07:46:18 +00007354
John McCalled976492009-12-04 22:46:56 +00007355/// Checks that the given nested-name qualifier used in a using decl
7356/// in the current context is appropriately related to the current
7357/// scope. If an error is found, diagnoses it and returns true.
7358bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7359 const CXXScopeSpec &SS,
7360 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007361 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007362
John McCall604e7f12009-12-08 07:46:18 +00007363 if (!CurContext->isRecord()) {
7364 // C++03 [namespace.udecl]p3:
7365 // C++0x [namespace.udecl]p8:
7366 // A using-declaration for a class member shall be a member-declaration.
7367
7368 // If we weren't able to compute a valid scope, it must be a
7369 // dependent class scope.
7370 if (!NamedContext || NamedContext->isRecord()) {
7371 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7372 << SS.getRange();
7373 return true;
7374 }
7375
7376 // Otherwise, everything is known to be fine.
7377 return false;
7378 }
7379
7380 // The current scope is a record.
7381
7382 // If the named context is dependent, we can't decide much.
7383 if (!NamedContext) {
7384 // FIXME: in C++0x, we can diagnose if we can prove that the
7385 // nested-name-specifier does not refer to a base class, which is
7386 // still possible in some cases.
7387
7388 // Otherwise we have to conservatively report that things might be
7389 // okay.
7390 return false;
7391 }
7392
7393 if (!NamedContext->isRecord()) {
7394 // Ideally this would point at the last name in the specifier,
7395 // but we don't have that level of source info.
7396 Diag(SS.getRange().getBegin(),
7397 diag::err_using_decl_nested_name_specifier_is_not_class)
7398 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7399 return true;
7400 }
7401
Douglas Gregor6fb07292010-12-21 07:41:49 +00007402 if (!NamedContext->isDependentContext() &&
7403 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7404 return true;
7405
Richard Smith80ad52f2013-01-02 11:42:31 +00007406 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007407 // C++0x [namespace.udecl]p3:
7408 // In a using-declaration used as a member-declaration, the
7409 // nested-name-specifier shall name a base class of the class
7410 // being defined.
7411
7412 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7413 cast<CXXRecordDecl>(NamedContext))) {
7414 if (CurContext == NamedContext) {
7415 Diag(NameLoc,
7416 diag::err_using_decl_nested_name_specifier_is_current_class)
7417 << SS.getRange();
7418 return true;
7419 }
7420
7421 Diag(SS.getRange().getBegin(),
7422 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7423 << (NestedNameSpecifier*) SS.getScopeRep()
7424 << cast<CXXRecordDecl>(CurContext)
7425 << SS.getRange();
7426 return true;
7427 }
7428
7429 return false;
7430 }
7431
7432 // C++03 [namespace.udecl]p4:
7433 // A using-declaration used as a member-declaration shall refer
7434 // to a member of a base class of the class being defined [etc.].
7435
7436 // Salient point: SS doesn't have to name a base class as long as
7437 // lookup only finds members from base classes. Therefore we can
7438 // diagnose here only if we can prove that that can't happen,
7439 // i.e. if the class hierarchies provably don't intersect.
7440
7441 // TODO: it would be nice if "definitely valid" results were cached
7442 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7443 // need to be repeated.
7444
7445 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007446 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007447
7448 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7449 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7450 Data->Bases.insert(Base);
7451 return true;
7452 }
7453
7454 bool hasDependentBases(const CXXRecordDecl *Class) {
7455 return !Class->forallBases(collect, this);
7456 }
7457
7458 /// Returns true if the base is dependent or is one of the
7459 /// accumulated base classes.
7460 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7461 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7462 return !Data->Bases.count(Base);
7463 }
7464
7465 bool mightShareBases(const CXXRecordDecl *Class) {
7466 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7467 }
7468 };
7469
7470 UserData Data;
7471
7472 // Returns false if we find a dependent base.
7473 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7474 return false;
7475
7476 // Returns false if the class has a dependent base or if it or one
7477 // of its bases is present in the base set of the current context.
7478 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7479 return false;
7480
7481 Diag(SS.getRange().getBegin(),
7482 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7483 << (NestedNameSpecifier*) SS.getScopeRep()
7484 << cast<CXXRecordDecl>(CurContext)
7485 << SS.getRange();
7486
7487 return true;
John McCalled976492009-12-04 22:46:56 +00007488}
7489
Richard Smith162e1c12011-04-15 14:24:37 +00007490Decl *Sema::ActOnAliasDeclaration(Scope *S,
7491 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007492 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007493 SourceLocation UsingLoc,
7494 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007495 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007496 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007497 // Skip up to the relevant declaration scope.
7498 while (S->getFlags() & Scope::TemplateParamScope)
7499 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007500 assert((S->getFlags() & Scope::DeclScope) &&
7501 "got alias-declaration outside of declaration scope");
7502
7503 if (Type.isInvalid())
7504 return 0;
7505
7506 bool Invalid = false;
7507 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7508 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007509 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007510
7511 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7512 return 0;
7513
7514 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007515 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007516 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007517 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7518 TInfo->getTypeLoc().getBeginLoc());
7519 }
Richard Smith162e1c12011-04-15 14:24:37 +00007520
7521 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7522 LookupName(Previous, S);
7523
7524 // Warn about shadowing the name of a template parameter.
7525 if (Previous.isSingleResult() &&
7526 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007527 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007528 Previous.clear();
7529 }
7530
7531 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7532 "name in alias declaration must be an identifier");
7533 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7534 Name.StartLocation,
7535 Name.Identifier, TInfo);
7536
7537 NewTD->setAccess(AS);
7538
7539 if (Invalid)
7540 NewTD->setInvalidDecl();
7541
Richard Smith6b3d3e52013-02-20 19:22:51 +00007542 ProcessDeclAttributeList(S, NewTD, AttrList);
7543
Richard Smith3e4c6c42011-05-05 21:57:07 +00007544 CheckTypedefForVariablyModifiedType(S, NewTD);
7545 Invalid |= NewTD->isInvalidDecl();
7546
Richard Smith162e1c12011-04-15 14:24:37 +00007547 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007548
7549 NamedDecl *NewND;
7550 if (TemplateParamLists.size()) {
7551 TypeAliasTemplateDecl *OldDecl = 0;
7552 TemplateParameterList *OldTemplateParams = 0;
7553
7554 if (TemplateParamLists.size() != 1) {
7555 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007556 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7557 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007558 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007559 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007560
7561 // Only consider previous declarations in the same scope.
7562 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7563 /*ExplicitInstantiationOrSpecialization*/false);
7564 if (!Previous.empty()) {
7565 Redeclaration = true;
7566
7567 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7568 if (!OldDecl && !Invalid) {
7569 Diag(UsingLoc, diag::err_redefinition_different_kind)
7570 << Name.Identifier;
7571
7572 NamedDecl *OldD = Previous.getRepresentativeDecl();
7573 if (OldD->getLocation().isValid())
7574 Diag(OldD->getLocation(), diag::note_previous_definition);
7575
7576 Invalid = true;
7577 }
7578
7579 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7580 if (TemplateParameterListsAreEqual(TemplateParams,
7581 OldDecl->getTemplateParameters(),
7582 /*Complain=*/true,
7583 TPL_TemplateMatch))
7584 OldTemplateParams = OldDecl->getTemplateParameters();
7585 else
7586 Invalid = true;
7587
7588 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7589 if (!Invalid &&
7590 !Context.hasSameType(OldTD->getUnderlyingType(),
7591 NewTD->getUnderlyingType())) {
7592 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7593 // but we can't reasonably accept it.
7594 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7595 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7596 if (OldTD->getLocation().isValid())
7597 Diag(OldTD->getLocation(), diag::note_previous_definition);
7598 Invalid = true;
7599 }
7600 }
7601 }
7602
7603 // Merge any previous default template arguments into our parameters,
7604 // and check the parameter list.
7605 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7606 TPC_TypeAliasTemplate))
7607 return 0;
7608
7609 TypeAliasTemplateDecl *NewDecl =
7610 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7611 Name.Identifier, TemplateParams,
7612 NewTD);
7613
7614 NewDecl->setAccess(AS);
7615
7616 if (Invalid)
7617 NewDecl->setInvalidDecl();
7618 else if (OldDecl)
7619 NewDecl->setPreviousDeclaration(OldDecl);
7620
7621 NewND = NewDecl;
7622 } else {
7623 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7624 NewND = NewTD;
7625 }
Richard Smith162e1c12011-04-15 14:24:37 +00007626
7627 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007628 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007629
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007630 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007631 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007632}
7633
John McCalld226f652010-08-21 09:40:31 +00007634Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007635 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007636 SourceLocation AliasLoc,
7637 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007638 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007639 SourceLocation IdentLoc,
7640 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007641
Anders Carlsson81c85c42009-03-28 23:53:49 +00007642 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007643 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7644 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007645
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007646 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007647 NamedDecl *PrevDecl
7648 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7649 ForRedeclaration);
7650 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7651 PrevDecl = 0;
7652
7653 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007654 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007655 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007656 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007657 // FIXME: At some point, we'll want to create the (redundant)
7658 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007659 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007660 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007661 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007662 }
Mike Stump1eb44332009-09-09 15:08:12 +00007663
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007664 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7665 diag::err_redefinition_different_kind;
7666 Diag(AliasLoc, DiagID) << Alias;
7667 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007668 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007669 }
7670
John McCalla24dc2e2009-11-17 02:14:36 +00007671 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007672 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007673
John McCallf36e02d2009-10-09 21:13:30 +00007674 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007675 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007676 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007677 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007678 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007679 }
Mike Stump1eb44332009-09-09 15:08:12 +00007680
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007681 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007682 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007683 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007684 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007685
John McCall3dbd3d52010-02-16 06:53:13 +00007686 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007687 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007688}
7689
Sean Hunt001cad92011-05-10 00:49:42 +00007690Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007691Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7692 CXXMethodDecl *MD) {
7693 CXXRecordDecl *ClassDecl = MD->getParent();
7694
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007695 // C++ [except.spec]p14:
7696 // An implicitly declared special member function (Clause 12) shall have an
7697 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007698 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007699 if (ClassDecl->isInvalidDecl())
7700 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007701
Sebastian Redl60618fa2011-03-12 11:50:43 +00007702 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007703 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7704 BEnd = ClassDecl->bases_end();
7705 B != BEnd; ++B) {
7706 if (B->isVirtual()) // Handled below.
7707 continue;
7708
Douglas Gregor18274032010-07-03 00:47:00 +00007709 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7710 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007711 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7712 // If this is a deleted function, add it anyway. This might be conformant
7713 // with the standard. This might not. I'm not sure. It might not matter.
7714 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007715 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007716 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007717 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007718
7719 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007720 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7721 BEnd = ClassDecl->vbases_end();
7722 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007723 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7724 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007725 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7726 // If this is a deleted function, add it anyway. This might be conformant
7727 // with the standard. This might not. I'm not sure. It might not matter.
7728 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007729 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007730 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007731 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007732
7733 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007734 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7735 FEnd = ClassDecl->field_end();
7736 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007737 if (F->hasInClassInitializer()) {
7738 if (Expr *E = F->getInClassInitializer())
7739 ExceptSpec.CalledExpr(E);
7740 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007741 // DR1351:
7742 // If the brace-or-equal-initializer of a non-static data member
7743 // invokes a defaulted default constructor of its class or of an
7744 // enclosing class in a potentially evaluated subexpression, the
7745 // program is ill-formed.
7746 //
7747 // This resolution is unworkable: the exception specification of the
7748 // default constructor can be needed in an unevaluated context, in
7749 // particular, in the operand of a noexcept-expression, and we can be
7750 // unable to compute an exception specification for an enclosed class.
7751 //
7752 // We do not allow an in-class initializer to require the evaluation
7753 // of the exception specification for any in-class initializer whose
7754 // definition is not lexically complete.
7755 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007756 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007757 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007758 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7759 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7760 // If this is a deleted function, add it anyway. This might be conformant
7761 // with the standard. This might not. I'm not sure. It might not matter.
7762 // In particular, the problem is that this function never gets called. It
7763 // might just be ill-formed because this function attempts to refer to
7764 // a deleted function here.
7765 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007766 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007767 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007768 }
John McCalle23cf432010-12-14 08:05:40 +00007769
Sean Hunt001cad92011-05-10 00:49:42 +00007770 return ExceptSpec;
7771}
7772
Richard Smith07b0fdc2013-03-18 21:12:30 +00007773Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007774Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7775 CXXRecordDecl *ClassDecl = CD->getParent();
7776
7777 // C++ [except.spec]p14:
7778 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007779 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007780 if (ClassDecl->isInvalidDecl())
7781 return ExceptSpec;
7782
7783 // Inherited constructor.
7784 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7785 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7786 // FIXME: Copying or moving the parameters could add extra exceptions to the
7787 // set, as could the default arguments for the inherited constructor. This
7788 // will be addressed when we implement the resolution of core issue 1351.
7789 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7790
7791 // Direct base-class constructors.
7792 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7793 BEnd = ClassDecl->bases_end();
7794 B != BEnd; ++B) {
7795 if (B->isVirtual()) // Handled below.
7796 continue;
7797
7798 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7800 if (BaseClassDecl == InheritedDecl)
7801 continue;
7802 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7803 if (Constructor)
7804 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7805 }
7806 }
7807
7808 // Virtual base-class constructors.
7809 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7810 BEnd = ClassDecl->vbases_end();
7811 B != BEnd; ++B) {
7812 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7813 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7814 if (BaseClassDecl == InheritedDecl)
7815 continue;
7816 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7817 if (Constructor)
7818 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7819 }
7820 }
7821
7822 // Field constructors.
7823 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7824 FEnd = ClassDecl->field_end();
7825 F != FEnd; ++F) {
7826 if (F->hasInClassInitializer()) {
7827 if (Expr *E = F->getInClassInitializer())
7828 ExceptSpec.CalledExpr(E);
7829 else if (!F->isInvalidDecl())
7830 Diag(CD->getLocation(),
7831 diag::err_in_class_initializer_references_def_ctor) << CD;
7832 } else if (const RecordType *RecordTy
7833 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7834 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7835 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7836 if (Constructor)
7837 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7838 }
7839 }
7840
Richard Smith07b0fdc2013-03-18 21:12:30 +00007841 return ExceptSpec;
7842}
7843
Richard Smithafb49182012-11-29 01:34:07 +00007844namespace {
7845/// RAII object to register a special member as being currently declared.
7846struct DeclaringSpecialMember {
7847 Sema &S;
7848 Sema::SpecialMemberDecl D;
7849 bool WasAlreadyBeingDeclared;
7850
7851 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7852 : S(S), D(RD, CSM) {
7853 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7854 if (WasAlreadyBeingDeclared)
7855 // This almost never happens, but if it does, ensure that our cache
7856 // doesn't contain a stale result.
7857 S.SpecialMemberCache.clear();
7858
7859 // FIXME: Register a note to be produced if we encounter an error while
7860 // declaring the special member.
7861 }
7862 ~DeclaringSpecialMember() {
7863 if (!WasAlreadyBeingDeclared)
7864 S.SpecialMembersBeingDeclared.erase(D);
7865 }
7866
7867 /// \brief Are we already trying to declare this special member?
7868 bool isAlreadyBeingDeclared() const {
7869 return WasAlreadyBeingDeclared;
7870 }
7871};
7872}
7873
Sean Hunt001cad92011-05-10 00:49:42 +00007874CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7875 CXXRecordDecl *ClassDecl) {
7876 // C++ [class.ctor]p5:
7877 // A default constructor for a class X is a constructor of class X
7878 // that can be called without an argument. If there is no
7879 // user-declared constructor for class X, a default constructor is
7880 // implicitly declared. An implicitly-declared default constructor
7881 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007882 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007883 "Should not build implicit default constructor!");
7884
Richard Smithafb49182012-11-29 01:34:07 +00007885 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7886 if (DSM.isAlreadyBeingDeclared())
7887 return 0;
7888
Richard Smith7756afa2012-06-10 05:43:50 +00007889 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7890 CXXDefaultConstructor,
7891 false);
7892
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007893 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007894 CanQualType ClassType
7895 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007896 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007897 DeclarationName Name
7898 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007899 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007900 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007901 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007902 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007903 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007904 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007905 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007906 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007907
7908 // Build an exception specification pointing back at this constructor.
7909 FunctionProtoType::ExtProtoInfo EPI;
7910 EPI.ExceptionSpecType = EST_Unevaluated;
7911 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007912 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007913
Richard Smithbc2a35d2012-12-08 08:32:28 +00007914 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7915 // constructors is easy to compute.
7916 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7917
7918 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007919 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007920
Douglas Gregor18274032010-07-03 00:47:00 +00007921 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007922 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007923
Douglas Gregor23c94db2010-07-02 17:43:08 +00007924 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007925 PushOnScopeChains(DefaultCon, S, false);
7926 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007927
Douglas Gregor32df23e2010-07-01 22:02:46 +00007928 return DefaultCon;
7929}
7930
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007931void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7932 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007933 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007934 !Constructor->doesThisDeclarationHaveABody() &&
7935 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007936 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007937
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007938 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007939 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007940
Eli Friedman9a14db32012-10-18 20:14:08 +00007941 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007942 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007943 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007944 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007945 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007946 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007947 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007948 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007949 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007950
7951 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007952 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007953
7954 Constructor->setUsed();
7955 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007956
7957 if (ASTMutationListener *L = getASTMutationListener()) {
7958 L->CompletedImplicitDefinition(Constructor);
7959 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007960}
7961
Richard Smith7a614d82011-06-11 17:19:42 +00007962void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007963 // Check that any explicitly-defaulted methods have exception specifications
7964 // compatible with their implicit exception specifications.
7965 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007966}
7967
Richard Smith4841ca52013-04-10 05:48:59 +00007968namespace {
7969/// Information on inheriting constructors to declare.
7970class InheritingConstructorInfo {
7971public:
7972 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7973 : SemaRef(SemaRef), Derived(Derived) {
7974 // Mark the constructors that we already have in the derived class.
7975 //
7976 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7977 // unless there is a user-declared constructor with the same signature in
7978 // the class where the using-declaration appears.
7979 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7980 }
7981
7982 void inheritAll(CXXRecordDecl *RD) {
7983 visitAll(RD, &InheritingConstructorInfo::inherit);
7984 }
7985
7986private:
7987 /// Information about an inheriting constructor.
7988 struct InheritingConstructor {
7989 InheritingConstructor()
7990 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7991
7992 /// If \c true, a constructor with this signature is already declared
7993 /// in the derived class.
7994 bool DeclaredInDerived;
7995
7996 /// The constructor which is inherited.
7997 const CXXConstructorDecl *BaseCtor;
7998
7999 /// The derived constructor we declared.
8000 CXXConstructorDecl *DerivedCtor;
8001 };
8002
8003 /// Inheriting constructors with a given canonical type. There can be at
8004 /// most one such non-template constructor, and any number of templated
8005 /// constructors.
8006 struct InheritingConstructorsForType {
8007 InheritingConstructor NonTemplate;
8008 llvm::SmallVector<
8009 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
8010
8011 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8012 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8013 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8014 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8015 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8016 false, S.TPL_TemplateMatch))
8017 return Templates[I].second;
8018 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8019 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008020 }
Richard Smith4841ca52013-04-10 05:48:59 +00008021
8022 return NonTemplate;
8023 }
8024 };
8025
8026 /// Get or create the inheriting constructor record for a constructor.
8027 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8028 QualType CtorType) {
8029 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8030 .getEntry(SemaRef, Ctor);
8031 }
8032
8033 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8034
8035 /// Process all constructors for a class.
8036 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8037 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8038 CtorE = RD->ctor_end();
8039 CtorIt != CtorE; ++CtorIt)
8040 (this->*Callback)(*CtorIt);
8041 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8042 I(RD->decls_begin()), E(RD->decls_end());
8043 I != E; ++I) {
8044 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8045 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8046 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008047 }
8048 }
Richard Smith4841ca52013-04-10 05:48:59 +00008049
8050 /// Note that a constructor (or constructor template) was declared in Derived.
8051 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8052 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8053 }
8054
8055 /// Inherit a single constructor.
8056 void inherit(const CXXConstructorDecl *Ctor) {
8057 const FunctionProtoType *CtorType =
8058 Ctor->getType()->castAs<FunctionProtoType>();
8059 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8060 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8061
8062 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8063
8064 // Core issue (no number yet): the ellipsis is always discarded.
8065 if (EPI.Variadic) {
8066 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8067 SemaRef.Diag(Ctor->getLocation(),
8068 diag::note_using_decl_constructor_ellipsis);
8069 EPI.Variadic = false;
8070 }
8071
8072 // Declare a constructor for each number of parameters.
8073 //
8074 // C++11 [class.inhctor]p1:
8075 // The candidate set of inherited constructors from the class X named in
8076 // the using-declaration consists of [... modulo defects ...] for each
8077 // constructor or constructor template of X, the set of constructors or
8078 // constructor templates that results from omitting any ellipsis parameter
8079 // specification and successively omitting parameters with a default
8080 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008081 unsigned MinParams = minParamsToInherit(Ctor);
8082 unsigned Params = Ctor->getNumParams();
8083 if (Params >= MinParams) {
8084 do
8085 declareCtor(UsingLoc, Ctor,
8086 SemaRef.Context.getFunctionType(
8087 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8088 while (Params > MinParams &&
8089 Ctor->getParamDecl(--Params)->hasDefaultArg());
8090 }
Richard Smith4841ca52013-04-10 05:48:59 +00008091 }
8092
8093 /// Find the using-declaration which specified that we should inherit the
8094 /// constructors of \p Base.
8095 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8096 // No fancy lookup required; just look for the base constructor name
8097 // directly within the derived class.
8098 ASTContext &Context = SemaRef.Context;
8099 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8100 Context.getCanonicalType(Context.getRecordType(Base)));
8101 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8102 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8103 }
8104
8105 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8106 // C++11 [class.inhctor]p3:
8107 // [F]or each constructor template in the candidate set of inherited
8108 // constructors, a constructor template is implicitly declared
8109 if (Ctor->getDescribedFunctionTemplate())
8110 return 0;
8111
8112 // For each non-template constructor in the candidate set of inherited
8113 // constructors other than a constructor having no parameters or a
8114 // copy/move constructor having a single parameter, a constructor is
8115 // implicitly declared [...]
8116 if (Ctor->getNumParams() == 0)
8117 return 1;
8118 if (Ctor->isCopyOrMoveConstructor())
8119 return 2;
8120
8121 // Per discussion on core reflector, never inherit a constructor which
8122 // would become a default, copy, or move constructor of Derived either.
8123 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8124 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8125 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8126 }
8127
8128 /// Declare a single inheriting constructor, inheriting the specified
8129 /// constructor, with the given type.
8130 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8131 QualType DerivedType) {
8132 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8133
8134 // C++11 [class.inhctor]p3:
8135 // ... a constructor is implicitly declared with the same constructor
8136 // characteristics unless there is a user-declared constructor with
8137 // the same signature in the class where the using-declaration appears
8138 if (Entry.DeclaredInDerived)
8139 return;
8140
8141 // C++11 [class.inhctor]p7:
8142 // If two using-declarations declare inheriting constructors with the
8143 // same signature, the program is ill-formed
8144 if (Entry.DerivedCtor) {
8145 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8146 // Only diagnose this once per constructor.
8147 if (Entry.DerivedCtor->isInvalidDecl())
8148 return;
8149 Entry.DerivedCtor->setInvalidDecl();
8150
8151 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8152 SemaRef.Diag(BaseCtor->getLocation(),
8153 diag::note_using_decl_constructor_conflict_current_ctor);
8154 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8155 diag::note_using_decl_constructor_conflict_previous_ctor);
8156 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8157 diag::note_using_decl_constructor_conflict_previous_using);
8158 } else {
8159 // Core issue (no number): if the same inheriting constructor is
8160 // produced by multiple base class constructors from the same base
8161 // class, the inheriting constructor is defined as deleted.
8162 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8163 }
8164
8165 return;
8166 }
8167
8168 ASTContext &Context = SemaRef.Context;
8169 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8170 Context.getCanonicalType(Context.getRecordType(Derived)));
8171 DeclarationNameInfo NameInfo(Name, UsingLoc);
8172
8173 TemplateParameterList *TemplateParams = 0;
8174 if (const FunctionTemplateDecl *FTD =
8175 BaseCtor->getDescribedFunctionTemplate()) {
8176 TemplateParams = FTD->getTemplateParameters();
8177 // We're reusing template parameters from a different DeclContext. This
8178 // is questionable at best, but works out because the template depth in
8179 // both places is guaranteed to be 0.
8180 // FIXME: Rebuild the template parameters in the new context, and
8181 // transform the function type to refer to them.
8182 }
8183
8184 // Build type source info pointing at the using-declaration. This is
8185 // required by template instantiation.
8186 TypeSourceInfo *TInfo =
8187 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8188 FunctionProtoTypeLoc ProtoLoc =
8189 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8190
8191 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8192 Context, Derived, UsingLoc, NameInfo, DerivedType,
8193 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8194 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8195
8196 // Build an unevaluated exception specification for this constructor.
8197 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8198 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8199 EPI.ExceptionSpecType = EST_Unevaluated;
8200 EPI.ExceptionSpecDecl = DerivedCtor;
8201 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8202 FPT->getArgTypes(), EPI));
8203
8204 // Build the parameter declarations.
8205 SmallVector<ParmVarDecl *, 16> ParamDecls;
8206 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8207 TypeSourceInfo *TInfo =
8208 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8209 ParmVarDecl *PD = ParmVarDecl::Create(
8210 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8211 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8212 PD->setScopeInfo(0, I);
8213 PD->setImplicit();
8214 ParamDecls.push_back(PD);
8215 ProtoLoc.setArg(I, PD);
8216 }
8217
8218 // Set up the new constructor.
8219 DerivedCtor->setAccess(BaseCtor->getAccess());
8220 DerivedCtor->setParams(ParamDecls);
8221 DerivedCtor->setInheritedConstructor(BaseCtor);
8222 if (BaseCtor->isDeleted())
8223 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8224
8225 // If this is a constructor template, build the template declaration.
8226 if (TemplateParams) {
8227 FunctionTemplateDecl *DerivedTemplate =
8228 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8229 TemplateParams, DerivedCtor);
8230 DerivedTemplate->setAccess(BaseCtor->getAccess());
8231 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8232 Derived->addDecl(DerivedTemplate);
8233 } else {
8234 Derived->addDecl(DerivedCtor);
8235 }
8236
8237 Entry.BaseCtor = BaseCtor;
8238 Entry.DerivedCtor = DerivedCtor;
8239 }
8240
8241 Sema &SemaRef;
8242 CXXRecordDecl *Derived;
8243 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8244 MapType Map;
8245};
8246}
8247
8248void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8249 // Defer declaring the inheriting constructors until the class is
8250 // instantiated.
8251 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008252 return;
8253
Richard Smith4841ca52013-04-10 05:48:59 +00008254 // Find base classes from which we might inherit constructors.
8255 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8256 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8257 BaseE = ClassDecl->bases_end();
8258 BaseIt != BaseE; ++BaseIt)
8259 if (BaseIt->getInheritConstructors())
8260 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008261
Richard Smith4841ca52013-04-10 05:48:59 +00008262 // Go no further if we're not inheriting any constructors.
8263 if (InheritedBases.empty())
8264 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008265
Richard Smith4841ca52013-04-10 05:48:59 +00008266 // Declare the inherited constructors.
8267 InheritingConstructorInfo ICI(*this, ClassDecl);
8268 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8269 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008270}
8271
Richard Smith07b0fdc2013-03-18 21:12:30 +00008272void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8273 CXXConstructorDecl *Constructor) {
8274 CXXRecordDecl *ClassDecl = Constructor->getParent();
8275 assert(Constructor->getInheritedConstructor() &&
8276 !Constructor->doesThisDeclarationHaveABody() &&
8277 !Constructor->isDeleted());
8278
8279 SynthesizedFunctionScope Scope(*this, Constructor);
8280 DiagnosticErrorTrap Trap(Diags);
8281 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8282 Trap.hasErrorOccurred()) {
8283 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8284 << Context.getTagDeclType(ClassDecl);
8285 Constructor->setInvalidDecl();
8286 return;
8287 }
8288
8289 SourceLocation Loc = Constructor->getLocation();
8290 Constructor->setBody(new (Context) CompoundStmt(Loc));
8291
8292 Constructor->setUsed();
8293 MarkVTableUsed(CurrentLocation, ClassDecl);
8294
8295 if (ASTMutationListener *L = getASTMutationListener()) {
8296 L->CompletedImplicitDefinition(Constructor);
8297 }
8298}
8299
8300
Sean Huntcb45a0f2011-05-12 22:46:25 +00008301Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008302Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8303 CXXRecordDecl *ClassDecl = MD->getParent();
8304
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008305 // C++ [except.spec]p14:
8306 // An implicitly declared special member function (Clause 12) shall have
8307 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008308 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008309 if (ClassDecl->isInvalidDecl())
8310 return ExceptSpec;
8311
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008312 // Direct base-class destructors.
8313 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8314 BEnd = ClassDecl->bases_end();
8315 B != BEnd; ++B) {
8316 if (B->isVirtual()) // Handled below.
8317 continue;
8318
8319 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008320 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008321 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008322 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008323
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008324 // Virtual base-class destructors.
8325 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8326 BEnd = ClassDecl->vbases_end();
8327 B != BEnd; ++B) {
8328 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008329 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008330 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008331 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008332
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008333 // Field destructors.
8334 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8335 FEnd = ClassDecl->field_end();
8336 F != FEnd; ++F) {
8337 if (const RecordType *RecordTy
8338 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008339 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008340 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008341 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008342
Sean Huntcb45a0f2011-05-12 22:46:25 +00008343 return ExceptSpec;
8344}
8345
8346CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8347 // C++ [class.dtor]p2:
8348 // If a class has no user-declared destructor, a destructor is
8349 // declared implicitly. An implicitly-declared destructor is an
8350 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008351 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008352
Richard Smithafb49182012-11-29 01:34:07 +00008353 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8354 if (DSM.isAlreadyBeingDeclared())
8355 return 0;
8356
Douglas Gregor4923aa22010-07-02 20:37:36 +00008357 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008358 CanQualType ClassType
8359 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008360 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008361 DeclarationName Name
8362 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008363 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008364 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008365 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8366 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008367 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008368 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008369 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008370 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008371
8372 // Build an exception specification pointing back at this destructor.
8373 FunctionProtoType::ExtProtoInfo EPI;
8374 EPI.ExceptionSpecType = EST_Unevaluated;
8375 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008376 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008377
Richard Smithbc2a35d2012-12-08 08:32:28 +00008378 AddOverriddenMethods(ClassDecl, Destructor);
8379
8380 // We don't need to use SpecialMemberIsTrivial here; triviality for
8381 // destructors is easy to compute.
8382 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8383
8384 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008385 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008386
Douglas Gregor4923aa22010-07-02 20:37:36 +00008387 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008388 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008389
Douglas Gregor4923aa22010-07-02 20:37:36 +00008390 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008391 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008392 PushOnScopeChains(Destructor, S, false);
8393 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008394
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008395 return Destructor;
8396}
8397
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008398void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008399 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008400 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008401 !Destructor->doesThisDeclarationHaveABody() &&
8402 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008403 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008404 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008405 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008406
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008407 if (Destructor->isInvalidDecl())
8408 return;
8409
Eli Friedman9a14db32012-10-18 20:14:08 +00008410 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008411
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008412 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008413 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8414 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008415
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008416 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008417 Diag(CurrentLocation, diag::note_member_synthesized_at)
8418 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8419
8420 Destructor->setInvalidDecl();
8421 return;
8422 }
8423
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008424 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008425 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008426 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008427 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008428 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008429
8430 if (ASTMutationListener *L = getASTMutationListener()) {
8431 L->CompletedImplicitDefinition(Destructor);
8432 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008433}
8434
Richard Smitha4156b82012-04-21 18:42:51 +00008435/// \brief Perform any semantic analysis which needs to be delayed until all
8436/// pending class member declarations have been parsed.
8437void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008438 // If the context is an invalid C++ class, just suppress these checks.
8439 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8440 if (Record->isInvalidDecl()) {
8441 DelayedDestructorExceptionSpecChecks.clear();
8442 return;
8443 }
8444 }
8445
Richard Smitha4156b82012-04-21 18:42:51 +00008446 // Perform any deferred checking of exception specifications for virtual
8447 // destructors.
8448 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8449 i != e; ++i) {
8450 const CXXDestructorDecl *Dtor =
8451 DelayedDestructorExceptionSpecChecks[i].first;
8452 assert(!Dtor->getParent()->isDependentType() &&
8453 "Should not ever add destructors of templates into the list.");
8454 CheckOverridingFunctionExceptionSpec(Dtor,
8455 DelayedDestructorExceptionSpecChecks[i].second);
8456 }
8457 DelayedDestructorExceptionSpecChecks.clear();
8458}
8459
Richard Smithb9d0b762012-07-27 04:22:15 +00008460void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8461 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008462 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008463 "adjusting dtor exception specs was introduced in c++11");
8464
Sebastian Redl0ee33912011-05-19 05:13:44 +00008465 // C++11 [class.dtor]p3:
8466 // A declaration of a destructor that does not have an exception-
8467 // specification is implicitly considered to have the same exception-
8468 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008469 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008470 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008471 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008472 return;
8473
Chandler Carruth3f224b22011-09-20 04:55:26 +00008474 // Replace the destructor's type, building off the existing one. Fortunately,
8475 // the only thing of interest in the destructor type is its extended info.
8476 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008477 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8478 EPI.ExceptionSpecType = EST_Unevaluated;
8479 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008480 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008481
Sebastian Redl0ee33912011-05-19 05:13:44 +00008482 // FIXME: If the destructor has a body that could throw, and the newly created
8483 // spec doesn't allow exceptions, we should emit a warning, because this
8484 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008485 // However, we don't have a body or an exception specification yet, so it
8486 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008487}
8488
Richard Smith8c889532012-11-14 00:50:40 +00008489/// When generating a defaulted copy or move assignment operator, if a field
8490/// should be copied with __builtin_memcpy rather than via explicit assignments,
8491/// do so. This optimization only applies for arrays of scalars, and for arrays
8492/// of class type where the selected copy/move-assignment operator is trivial.
8493static StmtResult
8494buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8495 Expr *To, Expr *From) {
8496 // Compute the size of the memory buffer to be copied.
8497 QualType SizeType = S.Context.getSizeType();
8498 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8499 S.Context.getTypeSizeInChars(T).getQuantity());
8500
8501 // Take the address of the field references for "from" and "to". We
8502 // directly construct UnaryOperators here because semantic analysis
8503 // does not permit us to take the address of an xvalue.
8504 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8505 S.Context.getPointerType(From->getType()),
8506 VK_RValue, OK_Ordinary, Loc);
8507 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8508 S.Context.getPointerType(To->getType()),
8509 VK_RValue, OK_Ordinary, Loc);
8510
8511 const Type *E = T->getBaseElementTypeUnsafe();
8512 bool NeedsCollectableMemCpy =
8513 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8514
8515 // Create a reference to the __builtin_objc_memmove_collectable function
8516 StringRef MemCpyName = NeedsCollectableMemCpy ?
8517 "__builtin_objc_memmove_collectable" :
8518 "__builtin_memcpy";
8519 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8520 Sema::LookupOrdinaryName);
8521 S.LookupName(R, S.TUScope, true);
8522
8523 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8524 if (!MemCpy)
8525 // Something went horribly wrong earlier, and we will have complained
8526 // about it.
8527 return StmtError();
8528
8529 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8530 VK_RValue, Loc, 0);
8531 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8532
8533 Expr *CallArgs[] = {
8534 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8535 };
8536 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8537 Loc, CallArgs, Loc);
8538
8539 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8540 return S.Owned(Call.takeAs<Stmt>());
8541}
8542
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008543/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008544/// \c To.
8545///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008546/// This routine is used to copy/move the members of a class with an
8547/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008548/// copied are arrays, this routine builds for loops to copy them.
8549///
8550/// \param S The Sema object used for type-checking.
8551///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008552/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008553///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008554/// \param T The type of the expressions being copied/moved. Both expressions
8555/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008556///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008557/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008558///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008559/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008560///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008561/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008562/// Otherwise, it's a non-static member subobject.
8563///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008564/// \param Copying Whether we're copying or moving.
8565///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008566/// \param Depth Internal parameter recording the depth of the recursion.
8567///
Richard Smith8c889532012-11-14 00:50:40 +00008568/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8569/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008570static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008571buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8572 Expr *To, Expr *From,
8573 bool CopyingBaseSubobject, bool Copying,
8574 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008575 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008576 // Each subobject is assigned in the manner appropriate to its type:
8577 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008578 // - if the subobject is of class type, as if by a call to operator= with
8579 // the subobject as the object expression and the corresponding
8580 // subobject of x as a single function argument (as if by explicit
8581 // qualification; that is, ignoring any possible virtual overriding
8582 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008583 //
8584 // C++03 [class.copy]p13:
8585 // - if the subobject is of class type, the copy assignment operator for
8586 // the class is used (as if by explicit qualification; that is,
8587 // ignoring any possible virtual overriding functions in more derived
8588 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008589 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8590 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008591
Douglas Gregor06a9f362010-05-01 20:49:11 +00008592 // Look for operator=.
8593 DeclarationName Name
8594 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8595 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8596 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008597
Richard Smith044c8aa2012-11-13 00:54:12 +00008598 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8599 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008600 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008601 LookupResult::Filter F = OpLookup.makeFilter();
8602 while (F.hasNext()) {
8603 NamedDecl *D = F.next();
8604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8605 if (Method->isCopyAssignmentOperator() ||
8606 (!Copying && Method->isMoveAssignmentOperator()))
8607 continue;
8608
8609 F.erase();
8610 }
8611 F.done();
John McCallb0207482010-03-16 06:11:48 +00008612 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008613
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008614 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008615 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008616 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008617 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008618 // ambiguities), we need to cast "this" to that subobject type; to
8619 // ensure that we don't go through the virtual call mechanism, we need
8620 // to qualify the operator= name with the base class (see below). However,
8621 // this means that if the base class has a protected copy assignment
8622 // operator, the protected member access check will fail. So, we
8623 // rewrite "protected" access to "public" access in this case, since we
8624 // know by construction that we're calling from a derived class.
8625 if (CopyingBaseSubobject) {
8626 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8627 L != LEnd; ++L) {
8628 if (L.getAccess() == AS_protected)
8629 L.setAccess(AS_public);
8630 }
8631 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008632
Douglas Gregor06a9f362010-05-01 20:49:11 +00008633 // Create the nested-name-specifier that will be used to qualify the
8634 // reference to operator=; this is required to suppress the virtual
8635 // call mechanism.
8636 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008637 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008638 SS.MakeTrivial(S.Context,
8639 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008640 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008641 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008642
Douglas Gregor06a9f362010-05-01 20:49:11 +00008643 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008644 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008645 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008646 /*TemplateKWLoc=*/SourceLocation(),
8647 /*FirstQualifierInScope=*/0,
8648 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008649 /*TemplateArgs=*/0,
8650 /*SuppressQualifierCheck=*/true);
8651 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008652 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008653
Douglas Gregor06a9f362010-05-01 20:49:11 +00008654 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008655
Richard Smith044c8aa2012-11-13 00:54:12 +00008656 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008657 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008658 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008659 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008660 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008661
Richard Smith8c889532012-11-14 00:50:40 +00008662 // If we built a call to a trivial 'operator=' while copying an array,
8663 // bail out. We'll replace the whole shebang with a memcpy.
8664 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8665 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8666 return StmtResult((Stmt*)0);
8667
Richard Smith044c8aa2012-11-13 00:54:12 +00008668 // Convert to an expression-statement, and clean up any produced
8669 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008670 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008671 }
John McCallb0207482010-03-16 06:11:48 +00008672
Richard Smith044c8aa2012-11-13 00:54:12 +00008673 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008674 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008675 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008676 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008677 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008678 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008679 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008680 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008681 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008682
8683 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008684 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008685
Douglas Gregor06a9f362010-05-01 20:49:11 +00008686 // Construct a loop over the array bounds, e.g.,
8687 //
8688 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8689 //
8690 // that will copy each of the array elements.
8691 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008692
Douglas Gregor06a9f362010-05-01 20:49:11 +00008693 // Create the iteration variable.
8694 IdentifierInfo *IterationVarName = 0;
8695 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008696 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008697 llvm::raw_svector_ostream OS(Str);
8698 OS << "__i" << Depth;
8699 IterationVarName = &S.Context.Idents.get(OS.str());
8700 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008701 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008702 IterationVarName, SizeType,
8703 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008704 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008705
Douglas Gregor06a9f362010-05-01 20:49:11 +00008706 // Initialize the iteration variable to zero.
8707 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008708 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008709
8710 // Create a reference to the iteration variable; we'll use this several
8711 // times throughout.
8712 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008713 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008714 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008715 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8716 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8717
Douglas Gregor06a9f362010-05-01 20:49:11 +00008718 // Create the DeclStmt that holds the iteration variable.
8719 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008720
Douglas Gregor06a9f362010-05-01 20:49:11 +00008721 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008722 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008723 IterationVarRefRVal,
8724 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008725 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008726 IterationVarRefRVal,
8727 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008728 if (!Copying) // Cast to rvalue
8729 From = CastForMoving(S, From);
8730
8731 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008732 StmtResult Copy =
8733 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8734 To, From, CopyingBaseSubobject,
8735 Copying, Depth + 1);
8736 // Bail out if copying fails or if we determined that we should use memcpy.
8737 if (Copy.isInvalid() || !Copy.get())
8738 return Copy;
8739
8740 // Create the comparison against the array bound.
8741 llvm::APInt Upper
8742 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8743 Expr *Comparison
8744 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8745 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8746 BO_NE, S.Context.BoolTy,
8747 VK_RValue, OK_Ordinary, Loc, false);
8748
8749 // Create the pre-increment of the iteration variable.
8750 Expr *Increment
8751 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8752 VK_LValue, OK_Ordinary, Loc);
8753
Douglas Gregor06a9f362010-05-01 20:49:11 +00008754 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008755 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008756 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008757 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008758 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008759}
8760
Richard Smith8c889532012-11-14 00:50:40 +00008761static StmtResult
8762buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8763 Expr *To, Expr *From,
8764 bool CopyingBaseSubobject, bool Copying) {
8765 // Maybe we should use a memcpy?
8766 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8767 T.isTriviallyCopyableType(S.Context))
8768 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8769
8770 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8771 CopyingBaseSubobject,
8772 Copying, 0));
8773
8774 // If we ended up picking a trivial assignment operator for an array of a
8775 // non-trivially-copyable class type, just emit a memcpy.
8776 if (!Result.isInvalid() && !Result.get())
8777 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8778
8779 return Result;
8780}
8781
Richard Smithb9d0b762012-07-27 04:22:15 +00008782Sema::ImplicitExceptionSpecification
8783Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8784 CXXRecordDecl *ClassDecl = MD->getParent();
8785
8786 ImplicitExceptionSpecification ExceptSpec(*this);
8787 if (ClassDecl->isInvalidDecl())
8788 return ExceptSpec;
8789
8790 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8791 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8792 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8793
Douglas Gregorb87786f2010-07-01 17:48:08 +00008794 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008795 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008796 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008797
8798 // It is unspecified whether or not an implicit copy assignment operator
8799 // attempts to deduplicate calls to assignment operators of virtual bases are
8800 // made. As such, this exception specification is effectively unspecified.
8801 // Based on a similar decision made for constness in C++0x, we're erring on
8802 // the side of assuming such calls to be made regardless of whether they
8803 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008804 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8805 BaseEnd = ClassDecl->bases_end();
8806 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008807 if (Base->isVirtual())
8808 continue;
8809
Douglas Gregora376d102010-07-02 21:50:04 +00008810 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008811 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008812 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8813 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008814 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008815 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008816
8817 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8818 BaseEnd = ClassDecl->vbases_end();
8819 Base != BaseEnd; ++Base) {
8820 CXXRecordDecl *BaseClassDecl
8821 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8822 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8823 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008824 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008825 }
8826
Douglas Gregorb87786f2010-07-01 17:48:08 +00008827 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8828 FieldEnd = ClassDecl->field_end();
8829 Field != FieldEnd;
8830 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008831 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008832 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8833 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008834 LookupCopyingAssignment(FieldClassDecl,
8835 ArgQuals | FieldType.getCVRQualifiers(),
8836 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008837 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008838 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008839 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008840
Richard Smithb9d0b762012-07-27 04:22:15 +00008841 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008842}
8843
8844CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8845 // Note: The following rules are largely analoguous to the copy
8846 // constructor rules. Note that virtual bases are not taken into account
8847 // for determining the argument type of the operator. Note also that
8848 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008849 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008850
Richard Smithafb49182012-11-29 01:34:07 +00008851 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8852 if (DSM.isAlreadyBeingDeclared())
8853 return 0;
8854
Sean Hunt30de05c2011-05-14 05:23:20 +00008855 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8856 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008857 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8858 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008859 ArgType = ArgType.withConst();
8860 ArgType = Context.getLValueReferenceType(ArgType);
8861
Richard Smitha8942d72013-05-07 03:19:20 +00008862 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8863 CXXCopyAssignment,
8864 Const);
8865
Douglas Gregord3c35902010-07-01 16:36:15 +00008866 // An implicitly-declared copy assignment operator is an inline public
8867 // member of its class.
8868 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008869 SourceLocation ClassLoc = ClassDecl->getLocation();
8870 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008871 CXXMethodDecl *CopyAssignment =
8872 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8873 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8874 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008875 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008876 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008877 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008878
8879 // Build an exception specification pointing back at this member.
8880 FunctionProtoType::ExtProtoInfo EPI;
8881 EPI.ExceptionSpecType = EST_Unevaluated;
8882 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008883 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008884
Douglas Gregord3c35902010-07-01 16:36:15 +00008885 // Add the parameter to the operator.
8886 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008887 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008888 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008889 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008890 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008891
Richard Smithbc2a35d2012-12-08 08:32:28 +00008892 AddOverriddenMethods(ClassDecl, CopyAssignment);
8893
8894 CopyAssignment->setTrivial(
8895 ClassDecl->needsOverloadResolutionForCopyAssignment()
8896 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8897 : ClassDecl->hasTrivialCopyAssignment());
8898
Richard Smitha8942d72013-05-07 03:19:20 +00008899 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008900 // .... If the class definition does not explicitly declare a copy
8901 // assignment operator, there is no user-declared move constructor, and
8902 // there is no user-declared move assignment operator, a copy assignment
8903 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008904 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008905 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008906
Richard Smithbc2a35d2012-12-08 08:32:28 +00008907 // Note that we have added this copy-assignment operator.
8908 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8909
8910 if (Scope *S = getScopeForContext(ClassDecl))
8911 PushOnScopeChains(CopyAssignment, S, false);
8912 ClassDecl->addDecl(CopyAssignment);
8913
Douglas Gregord3c35902010-07-01 16:36:15 +00008914 return CopyAssignment;
8915}
8916
Richard Smith36155c12013-06-13 03:23:42 +00008917/// Diagnose an implicit copy operation for a class which is odr-used, but
8918/// which is deprecated because the class has a user-declared copy constructor,
8919/// copy assignment operator, or destructor.
8920static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8921 SourceLocation UseLoc) {
8922 assert(CopyOp->isImplicit());
8923
8924 CXXRecordDecl *RD = CopyOp->getParent();
8925 CXXMethodDecl *UserDeclaredOperation = 0;
8926
8927 // In Microsoft mode, assignment operations don't affect constructors and
8928 // vice versa.
8929 if (RD->hasUserDeclaredDestructor()) {
8930 UserDeclaredOperation = RD->getDestructor();
8931 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8932 RD->hasUserDeclaredCopyConstructor() &&
8933 !S.getLangOpts().MicrosoftMode) {
8934 // Find any user-declared copy constructor.
8935 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8936 E = RD->ctor_end(); I != E; ++I) {
8937 if (I->isCopyConstructor()) {
8938 UserDeclaredOperation = *I;
8939 break;
8940 }
8941 }
8942 assert(UserDeclaredOperation);
8943 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8944 RD->hasUserDeclaredCopyAssignment() &&
8945 !S.getLangOpts().MicrosoftMode) {
8946 // Find any user-declared move assignment operator.
8947 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8948 E = RD->method_end(); I != E; ++I) {
8949 if (I->isCopyAssignmentOperator()) {
8950 UserDeclaredOperation = *I;
8951 break;
8952 }
8953 }
8954 assert(UserDeclaredOperation);
8955 }
8956
8957 if (UserDeclaredOperation) {
8958 S.Diag(UserDeclaredOperation->getLocation(),
8959 diag::warn_deprecated_copy_operation)
8960 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8961 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8962 S.Diag(UseLoc, diag::note_member_synthesized_at)
8963 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8964 : Sema::CXXCopyAssignment)
8965 << RD;
8966 }
8967}
8968
Douglas Gregor06a9f362010-05-01 20:49:11 +00008969void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8970 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008971 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008972 CopyAssignOperator->isOverloadedOperator() &&
8973 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008974 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8975 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008976 "DefineImplicitCopyAssignment called for wrong function");
8977
8978 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8979
8980 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8981 CopyAssignOperator->setInvalidDecl();
8982 return;
8983 }
Richard Smith36155c12013-06-13 03:23:42 +00008984
8985 // C++11 [class.copy]p18:
8986 // The [definition of an implicitly declared copy assignment operator] is
8987 // deprecated if the class has a user-declared copy constructor or a
8988 // user-declared destructor.
8989 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8990 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8991
Douglas Gregor06a9f362010-05-01 20:49:11 +00008992 CopyAssignOperator->setUsed();
8993
Eli Friedman9a14db32012-10-18 20:14:08 +00008994 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008995 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008996
8997 // C++0x [class.copy]p30:
8998 // The implicitly-defined or explicitly-defaulted copy assignment operator
8999 // for a non-union class X performs memberwise copy assignment of its
9000 // subobjects. The direct base classes of X are assigned first, in the
9001 // order of their declaration in the base-specifier-list, and then the
9002 // immediate non-static data members of X are assigned, in the order in
9003 // which they were declared in the class definition.
9004
9005 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009006 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009007
9008 // The parameter for the "other" object, which we are copying from.
9009 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9010 Qualifiers OtherQuals = Other->getType().getQualifiers();
9011 QualType OtherRefType = Other->getType();
9012 if (const LValueReferenceType *OtherRef
9013 = OtherRefType->getAs<LValueReferenceType>()) {
9014 OtherRefType = OtherRef->getPointeeType();
9015 OtherQuals = OtherRefType.getQualifiers();
9016 }
9017
9018 // Our location for everything implicitly-generated.
9019 SourceLocation Loc = CopyAssignOperator->getLocation();
9020
9021 // Construct a reference to the "other" object. We'll be using this
9022 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00009023 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009024 assert(OtherRef && "Reference to parameter cannot fail!");
9025
9026 // Construct the "this" pointer. We'll be using this throughout the generated
9027 // ASTs.
9028 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9029 assert(This && "Reference to this cannot fail!");
9030
9031 // Assign base classes.
9032 bool Invalid = false;
9033 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9034 E = ClassDecl->bases_end(); Base != E; ++Base) {
9035 // Form the assignment:
9036 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9037 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009038 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009039 Invalid = true;
9040 continue;
9041 }
9042
John McCallf871d0c2010-08-07 06:22:56 +00009043 CXXCastPath BasePath;
9044 BasePath.push_back(Base);
9045
Douglas Gregor06a9f362010-05-01 20:49:11 +00009046 // Construct the "from" expression, which is an implicit cast to the
9047 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00009048 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00009049 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
9050 CK_UncheckedDerivedToBase,
9051 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009052
9053 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00009054 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009055
9056 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00009057 To = ImpCastExprToType(To.take(),
9058 Context.getCVRQualifiedType(BaseType,
9059 CopyAssignOperator->getTypeQualifiers()),
9060 CK_UncheckedDerivedToBase,
9061 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009062
9063 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009064 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00009065 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009066 /*CopyingBaseSubobject=*/true,
9067 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009068 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009069 Diag(CurrentLocation, diag::note_member_synthesized_at)
9070 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9071 CopyAssignOperator->setInvalidDecl();
9072 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009073 }
9074
9075 // Success! Record the copy.
9076 Statements.push_back(Copy.takeAs<Expr>());
9077 }
9078
Douglas Gregor06a9f362010-05-01 20:49:11 +00009079 // Assign non-static members.
9080 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9081 FieldEnd = ClassDecl->field_end();
9082 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009083 if (Field->isUnnamedBitfield())
9084 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009085
9086 if (Field->isInvalidDecl()) {
9087 Invalid = true;
9088 continue;
9089 }
9090
Douglas Gregor06a9f362010-05-01 20:49:11 +00009091 // Check for members of reference type; we can't copy those.
9092 if (Field->getType()->isReferenceType()) {
9093 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9094 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9095 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009096 Diag(CurrentLocation, diag::note_member_synthesized_at)
9097 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009098 Invalid = true;
9099 continue;
9100 }
9101
9102 // Check for members of const-qualified, non-class type.
9103 QualType BaseType = Context.getBaseElementType(Field->getType());
9104 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9105 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9106 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9107 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009108 Diag(CurrentLocation, diag::note_member_synthesized_at)
9109 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009110 Invalid = true;
9111 continue;
9112 }
John McCallb77115d2011-06-17 00:18:42 +00009113
9114 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009115 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9116 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009117
9118 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009119 if (FieldType->isIncompleteArrayType()) {
9120 assert(ClassDecl->hasFlexibleArrayMember() &&
9121 "Incomplete array type is not valid");
9122 continue;
9123 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009124
9125 // Build references to the field in the object we're copying from and to.
9126 CXXScopeSpec SS; // Intentionally empty
9127 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9128 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009129 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009130 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009131 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009132 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009133 SS, SourceLocation(), 0,
9134 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009135 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009136 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009137 SS, SourceLocation(), 0,
9138 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009139 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9140 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009141
Douglas Gregor06a9f362010-05-01 20:49:11 +00009142 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009143 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009144 To.get(), From.get(),
9145 /*CopyingBaseSubobject=*/false,
9146 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009147 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009148 Diag(CurrentLocation, diag::note_member_synthesized_at)
9149 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9150 CopyAssignOperator->setInvalidDecl();
9151 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009152 }
9153
9154 // Success! Record the copy.
9155 Statements.push_back(Copy.takeAs<Stmt>());
9156 }
9157
9158 if (!Invalid) {
9159 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009160 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009161
John McCall60d7b3a2010-08-24 06:29:42 +00009162 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009163 if (Return.isInvalid())
9164 Invalid = true;
9165 else {
9166 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009167
9168 if (Trap.hasErrorOccurred()) {
9169 Diag(CurrentLocation, diag::note_member_synthesized_at)
9170 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9171 Invalid = true;
9172 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009173 }
9174 }
9175
9176 if (Invalid) {
9177 CopyAssignOperator->setInvalidDecl();
9178 return;
9179 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009180
9181 StmtResult Body;
9182 {
9183 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009184 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009185 /*isStmtExpr=*/false);
9186 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9187 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009188 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009189
9190 if (ASTMutationListener *L = getASTMutationListener()) {
9191 L->CompletedImplicitDefinition(CopyAssignOperator);
9192 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009193}
9194
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009195Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009196Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9197 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009198
Richard Smithb9d0b762012-07-27 04:22:15 +00009199 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009200 if (ClassDecl->isInvalidDecl())
9201 return ExceptSpec;
9202
9203 // C++0x [except.spec]p14:
9204 // An implicitly declared special member function (Clause 12) shall have an
9205 // exception-specification. [...]
9206
9207 // It is unspecified whether or not an implicit move assignment operator
9208 // attempts to deduplicate calls to assignment operators of virtual bases are
9209 // made. As such, this exception specification is effectively unspecified.
9210 // Based on a similar decision made for constness in C++0x, we're erring on
9211 // the side of assuming such calls to be made regardless of whether they
9212 // actually happen.
9213 // Note that a move constructor is not implicitly declared when there are
9214 // virtual bases, but it can still be user-declared and explicitly defaulted.
9215 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9216 BaseEnd = ClassDecl->bases_end();
9217 Base != BaseEnd; ++Base) {
9218 if (Base->isVirtual())
9219 continue;
9220
9221 CXXRecordDecl *BaseClassDecl
9222 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9223 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009224 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009225 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009226 }
9227
9228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9229 BaseEnd = ClassDecl->vbases_end();
9230 Base != BaseEnd; ++Base) {
9231 CXXRecordDecl *BaseClassDecl
9232 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9233 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009234 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009235 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009236 }
9237
9238 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9239 FieldEnd = ClassDecl->field_end();
9240 Field != FieldEnd;
9241 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009242 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009243 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009244 if (CXXMethodDecl *MoveAssign =
9245 LookupMovingAssignment(FieldClassDecl,
9246 FieldType.getCVRQualifiers(),
9247 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009248 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009249 }
9250 }
9251
9252 return ExceptSpec;
9253}
9254
Richard Smith1c931be2012-04-02 18:40:40 +00009255/// Determine whether the class type has any direct or indirect virtual base
9256/// classes which have a non-trivial move assignment operator.
9257static bool
9258hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9259 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9260 BaseEnd = ClassDecl->vbases_end();
9261 Base != BaseEnd; ++Base) {
9262 CXXRecordDecl *BaseClass =
9263 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9264
9265 // Try to declare the move assignment. If it would be deleted, then the
9266 // class does not have a non-trivial move assignment.
9267 if (BaseClass->needsImplicitMoveAssignment())
9268 S.DeclareImplicitMoveAssignment(BaseClass);
9269
Richard Smith426391c2012-11-16 00:53:38 +00009270 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009271 return true;
9272 }
9273
9274 return false;
9275}
9276
9277/// Determine whether the given type either has a move constructor or is
9278/// trivially copyable.
9279static bool
9280hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9281 Type = S.Context.getBaseElementType(Type);
9282
9283 // FIXME: Technically, non-trivially-copyable non-class types, such as
9284 // reference types, are supposed to return false here, but that appears
9285 // to be a standard defect.
9286 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009287 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009288 return true;
9289
9290 if (Type.isTriviallyCopyableType(S.Context))
9291 return true;
9292
9293 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009294 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9295 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009296 if (ClassDecl->needsImplicitMoveConstructor())
9297 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009298 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009299 }
9300
Richard Smithe5411b72012-12-01 02:35:44 +00009301 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9302 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009303 if (ClassDecl->needsImplicitMoveAssignment())
9304 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009305 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009306}
9307
9308/// Determine whether all non-static data members and direct or virtual bases
9309/// of class \p ClassDecl have either a move operation, or are trivially
9310/// copyable.
9311static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9312 bool IsConstructor) {
9313 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9314 BaseEnd = ClassDecl->bases_end();
9315 Base != BaseEnd; ++Base) {
9316 if (Base->isVirtual())
9317 continue;
9318
9319 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9320 return false;
9321 }
9322
9323 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9324 BaseEnd = ClassDecl->vbases_end();
9325 Base != BaseEnd; ++Base) {
9326 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9327 return false;
9328 }
9329
9330 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9331 FieldEnd = ClassDecl->field_end();
9332 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009333 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009334 return false;
9335 }
9336
9337 return true;
9338}
9339
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009340CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009341 // C++11 [class.copy]p20:
9342 // If the definition of a class X does not explicitly declare a move
9343 // assignment operator, one will be implicitly declared as defaulted
9344 // if and only if:
9345 //
9346 // - [first 4 bullets]
9347 assert(ClassDecl->needsImplicitMoveAssignment());
9348
Richard Smithafb49182012-11-29 01:34:07 +00009349 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9350 if (DSM.isAlreadyBeingDeclared())
9351 return 0;
9352
Richard Smith1c931be2012-04-02 18:40:40 +00009353 // [Checked after we build the declaration]
9354 // - the move assignment operator would not be implicitly defined as
9355 // deleted,
9356
9357 // [DR1402]:
9358 // - X has no direct or indirect virtual base class with a non-trivial
9359 // move assignment operator, and
9360 // - each of X's non-static data members and direct or virtual base classes
9361 // has a type that either has a move assignment operator or is trivially
9362 // copyable.
9363 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9364 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9365 ClassDecl->setFailedImplicitMoveAssignment();
9366 return 0;
9367 }
9368
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009369 // Note: The following rules are largely analoguous to the move
9370 // constructor rules.
9371
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009372 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9373 QualType RetType = Context.getLValueReferenceType(ArgType);
9374 ArgType = Context.getRValueReferenceType(ArgType);
9375
Richard Smitha8942d72013-05-07 03:19:20 +00009376 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9377 CXXMoveAssignment,
9378 false);
9379
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009380 // An implicitly-declared move assignment operator is an inline public
9381 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9383 SourceLocation ClassLoc = ClassDecl->getLocation();
9384 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009385 CXXMethodDecl *MoveAssignment =
9386 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9387 /*TInfo=*/0, /*StorageClass=*/SC_None,
9388 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009389 MoveAssignment->setAccess(AS_public);
9390 MoveAssignment->setDefaulted();
9391 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009392
Richard Smithb9d0b762012-07-27 04:22:15 +00009393 // Build an exception specification pointing back at this member.
9394 FunctionProtoType::ExtProtoInfo EPI;
9395 EPI.ExceptionSpecType = EST_Unevaluated;
9396 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009397 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009398
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009399 // Add the parameter to the operator.
9400 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9401 ClassLoc, ClassLoc, /*Id=*/0,
9402 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009403 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009404 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009405
Richard Smithbc2a35d2012-12-08 08:32:28 +00009406 AddOverriddenMethods(ClassDecl, MoveAssignment);
9407
9408 MoveAssignment->setTrivial(
9409 ClassDecl->needsOverloadResolutionForMoveAssignment()
9410 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9411 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009412
9413 // C++0x [class.copy]p9:
9414 // If the definition of a class X does not explicitly declare a move
9415 // assignment operator, one will be implicitly declared as defaulted if and
9416 // only if:
9417 // [...]
9418 // - the move assignment operator would not be implicitly defined as
9419 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009420 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009421 // Cache this result so that we don't try to generate this over and over
9422 // on every lookup, leaking memory and wasting time.
9423 ClassDecl->setFailedImplicitMoveAssignment();
9424 return 0;
9425 }
9426
Richard Smithbc2a35d2012-12-08 08:32:28 +00009427 // Note that we have added this copy-assignment operator.
9428 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9429
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009430 if (Scope *S = getScopeForContext(ClassDecl))
9431 PushOnScopeChains(MoveAssignment, S, false);
9432 ClassDecl->addDecl(MoveAssignment);
9433
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009434 return MoveAssignment;
9435}
9436
9437void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9438 CXXMethodDecl *MoveAssignOperator) {
9439 assert((MoveAssignOperator->isDefaulted() &&
9440 MoveAssignOperator->isOverloadedOperator() &&
9441 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009442 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9443 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009444 "DefineImplicitMoveAssignment called for wrong function");
9445
9446 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9447
9448 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9449 MoveAssignOperator->setInvalidDecl();
9450 return;
9451 }
9452
9453 MoveAssignOperator->setUsed();
9454
Eli Friedman9a14db32012-10-18 20:14:08 +00009455 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009456 DiagnosticErrorTrap Trap(Diags);
9457
9458 // C++0x [class.copy]p28:
9459 // The implicitly-defined or move assignment operator for a non-union class
9460 // X performs memberwise move assignment of its subobjects. The direct base
9461 // classes of X are assigned first, in the order of their declaration in the
9462 // base-specifier-list, and then the immediate non-static data members of X
9463 // are assigned, in the order in which they were declared in the class
9464 // definition.
9465
9466 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009467 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009468
9469 // The parameter for the "other" object, which we are move from.
9470 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9471 QualType OtherRefType = Other->getType()->
9472 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009473 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009474 "Bad argument type of defaulted move assignment");
9475
9476 // Our location for everything implicitly-generated.
9477 SourceLocation Loc = MoveAssignOperator->getLocation();
9478
9479 // Construct a reference to the "other" object. We'll be using this
9480 // throughout the generated ASTs.
9481 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9482 assert(OtherRef && "Reference to parameter cannot fail!");
9483 // Cast to rvalue.
9484 OtherRef = CastForMoving(*this, OtherRef);
9485
9486 // Construct the "this" pointer. We'll be using this throughout the generated
9487 // ASTs.
9488 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9489 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009490
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009491 // Assign base classes.
9492 bool Invalid = false;
9493 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9494 E = ClassDecl->bases_end(); Base != E; ++Base) {
9495 // Form the assignment:
9496 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9497 QualType BaseType = Base->getType().getUnqualifiedType();
9498 if (!BaseType->isRecordType()) {
9499 Invalid = true;
9500 continue;
9501 }
9502
9503 CXXCastPath BasePath;
9504 BasePath.push_back(Base);
9505
9506 // Construct the "from" expression, which is an implicit cast to the
9507 // appropriately-qualified base type.
9508 Expr *From = OtherRef;
9509 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009510 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009511
9512 // Dereference "this".
9513 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9514
9515 // Implicitly cast "this" to the appropriately-qualified base type.
9516 To = ImpCastExprToType(To.take(),
9517 Context.getCVRQualifiedType(BaseType,
9518 MoveAssignOperator->getTypeQualifiers()),
9519 CK_UncheckedDerivedToBase,
9520 VK_LValue, &BasePath);
9521
9522 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009523 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009524 To.get(), From,
9525 /*CopyingBaseSubobject=*/true,
9526 /*Copying=*/false);
9527 if (Move.isInvalid()) {
9528 Diag(CurrentLocation, diag::note_member_synthesized_at)
9529 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9530 MoveAssignOperator->setInvalidDecl();
9531 return;
9532 }
9533
9534 // Success! Record the move.
9535 Statements.push_back(Move.takeAs<Expr>());
9536 }
9537
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009538 // Assign non-static members.
9539 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9540 FieldEnd = ClassDecl->field_end();
9541 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009542 if (Field->isUnnamedBitfield())
9543 continue;
9544
Eli Friedman8150da32013-06-07 01:48:56 +00009545 if (Field->isInvalidDecl()) {
9546 Invalid = true;
9547 continue;
9548 }
9549
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009550 // Check for members of reference type; we can't move those.
9551 if (Field->getType()->isReferenceType()) {
9552 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9553 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9554 Diag(Field->getLocation(), diag::note_declared_at);
9555 Diag(CurrentLocation, diag::note_member_synthesized_at)
9556 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9557 Invalid = true;
9558 continue;
9559 }
9560
9561 // Check for members of const-qualified, non-class type.
9562 QualType BaseType = Context.getBaseElementType(Field->getType());
9563 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9564 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9565 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9566 Diag(Field->getLocation(), diag::note_declared_at);
9567 Diag(CurrentLocation, diag::note_member_synthesized_at)
9568 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9569 Invalid = true;
9570 continue;
9571 }
9572
9573 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009574 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9575 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009576
9577 QualType FieldType = Field->getType().getNonReferenceType();
9578 if (FieldType->isIncompleteArrayType()) {
9579 assert(ClassDecl->hasFlexibleArrayMember() &&
9580 "Incomplete array type is not valid");
9581 continue;
9582 }
9583
9584 // Build references to the field in the object we're copying from and to.
9585 CXXScopeSpec SS; // Intentionally empty
9586 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9587 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009588 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009589 MemberLookup.resolveKind();
9590 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9591 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009592 SS, SourceLocation(), 0,
9593 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009594 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9595 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009596 SS, SourceLocation(), 0,
9597 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009598 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9599 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9600
9601 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9602 "Member reference with rvalue base must be rvalue except for reference "
9603 "members, which aren't allowed for move assignment.");
9604
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009605 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009606 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009607 To.get(), From.get(),
9608 /*CopyingBaseSubobject=*/false,
9609 /*Copying=*/false);
9610 if (Move.isInvalid()) {
9611 Diag(CurrentLocation, diag::note_member_synthesized_at)
9612 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9613 MoveAssignOperator->setInvalidDecl();
9614 return;
9615 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009616
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009617 // Success! Record the copy.
9618 Statements.push_back(Move.takeAs<Stmt>());
9619 }
9620
9621 if (!Invalid) {
9622 // Add a "return *this;"
9623 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9624
9625 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9626 if (Return.isInvalid())
9627 Invalid = true;
9628 else {
9629 Statements.push_back(Return.takeAs<Stmt>());
9630
9631 if (Trap.hasErrorOccurred()) {
9632 Diag(CurrentLocation, diag::note_member_synthesized_at)
9633 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9634 Invalid = true;
9635 }
9636 }
9637 }
9638
9639 if (Invalid) {
9640 MoveAssignOperator->setInvalidDecl();
9641 return;
9642 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009643
9644 StmtResult Body;
9645 {
9646 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009647 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009648 /*isStmtExpr=*/false);
9649 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9650 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009651 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9652
9653 if (ASTMutationListener *L = getASTMutationListener()) {
9654 L->CompletedImplicitDefinition(MoveAssignOperator);
9655 }
9656}
9657
Richard Smithb9d0b762012-07-27 04:22:15 +00009658Sema::ImplicitExceptionSpecification
9659Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9660 CXXRecordDecl *ClassDecl = MD->getParent();
9661
9662 ImplicitExceptionSpecification ExceptSpec(*this);
9663 if (ClassDecl->isInvalidDecl())
9664 return ExceptSpec;
9665
9666 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9667 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9668 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9669
Douglas Gregor0d405db2010-07-01 20:59:04 +00009670 // C++ [except.spec]p14:
9671 // An implicitly declared special member function (Clause 12) shall have an
9672 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009673 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9674 BaseEnd = ClassDecl->bases_end();
9675 Base != BaseEnd;
9676 ++Base) {
9677 // Virtual bases are handled below.
9678 if (Base->isVirtual())
9679 continue;
9680
Douglas Gregor22584312010-07-02 23:41:54 +00009681 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009682 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009683 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009684 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009685 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009686 }
9687 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9688 BaseEnd = ClassDecl->vbases_end();
9689 Base != BaseEnd;
9690 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009691 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009692 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009693 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009694 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009695 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009696 }
9697 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9698 FieldEnd = ClassDecl->field_end();
9699 Field != FieldEnd;
9700 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009701 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009702 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9703 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009704 LookupCopyingConstructor(FieldClassDecl,
9705 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009706 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009707 }
9708 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009709
Richard Smithb9d0b762012-07-27 04:22:15 +00009710 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009711}
9712
9713CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9714 CXXRecordDecl *ClassDecl) {
9715 // C++ [class.copy]p4:
9716 // If the class definition does not explicitly declare a copy
9717 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009718 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009719
Richard Smithafb49182012-11-29 01:34:07 +00009720 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9721 if (DSM.isAlreadyBeingDeclared())
9722 return 0;
9723
Sean Hunt49634cf2011-05-13 06:10:58 +00009724 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9725 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009726 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009727 if (Const)
9728 ArgType = ArgType.withConst();
9729 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009730
Richard Smith7756afa2012-06-10 05:43:50 +00009731 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9732 CXXCopyConstructor,
9733 Const);
9734
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009735 DeclarationName Name
9736 = Context.DeclarationNames.getCXXConstructorName(
9737 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009738 SourceLocation ClassLoc = ClassDecl->getLocation();
9739 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009740
9741 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009742 // member of its class.
9743 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009744 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009745 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009746 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009747 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009748 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009749
Richard Smithb9d0b762012-07-27 04:22:15 +00009750 // Build an exception specification pointing back at this member.
9751 FunctionProtoType::ExtProtoInfo EPI;
9752 EPI.ExceptionSpecType = EST_Unevaluated;
9753 EPI.ExceptionSpecDecl = CopyConstructor;
9754 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009755 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009756
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009757 // Add the parameter to the constructor.
9758 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009759 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009760 /*IdentifierInfo=*/0,
9761 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009762 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009763 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009764
Richard Smithbc2a35d2012-12-08 08:32:28 +00009765 CopyConstructor->setTrivial(
9766 ClassDecl->needsOverloadResolutionForCopyConstructor()
9767 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9768 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009769
Nico Weberafcc96a2012-01-23 03:19:29 +00009770 // C++11 [class.copy]p8:
9771 // ... If the class definition does not explicitly declare a copy
9772 // constructor, there is no user-declared move constructor, and there is no
9773 // user-declared move assignment operator, a copy constructor is implicitly
9774 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009775 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009776 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009777
Richard Smithbc2a35d2012-12-08 08:32:28 +00009778 // Note that we have declared this constructor.
9779 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9780
9781 if (Scope *S = getScopeForContext(ClassDecl))
9782 PushOnScopeChains(CopyConstructor, S, false);
9783 ClassDecl->addDecl(CopyConstructor);
9784
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009785 return CopyConstructor;
9786}
9787
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009788void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009789 CXXConstructorDecl *CopyConstructor) {
9790 assert((CopyConstructor->isDefaulted() &&
9791 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009792 !CopyConstructor->doesThisDeclarationHaveABody() &&
9793 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009794 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009795
Anders Carlsson63010a72010-04-23 16:24:12 +00009796 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009797 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009798
Richard Smith36155c12013-06-13 03:23:42 +00009799 // C++11 [class.copy]p7:
9800 // The [definition of an implicitly declared copy constructro] is
9801 // deprecated if the class has a user-declared copy assignment operator
9802 // or a user-declared destructor.
9803 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9804 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9805
Eli Friedman9a14db32012-10-18 20:14:08 +00009806 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009807 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009808
David Blaikie93c86172013-01-17 05:26:25 +00009809 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009810 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009811 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009812 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009813 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009814 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009815 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009816 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9817 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009818 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009819 /*isStmtExpr=*/false)
9820 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009821 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009822 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009823
9824 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009825 if (ASTMutationListener *L = getASTMutationListener()) {
9826 L->CompletedImplicitDefinition(CopyConstructor);
9827 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009828}
9829
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009830Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009831Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9832 CXXRecordDecl *ClassDecl = MD->getParent();
9833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 // C++ [except.spec]p14:
9835 // An implicitly declared special member function (Clause 12) shall have an
9836 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009837 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009838 if (ClassDecl->isInvalidDecl())
9839 return ExceptSpec;
9840
9841 // Direct base-class constructors.
9842 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9843 BEnd = ClassDecl->bases_end();
9844 B != BEnd; ++B) {
9845 if (B->isVirtual()) // Handled below.
9846 continue;
9847
9848 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9849 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009850 CXXConstructorDecl *Constructor =
9851 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009852 // If this is a deleted function, add it anyway. This might be conformant
9853 // with the standard. This might not. I'm not sure. It might not matter.
9854 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009855 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009856 }
9857 }
9858
9859 // Virtual base-class constructors.
9860 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9861 BEnd = ClassDecl->vbases_end();
9862 B != BEnd; ++B) {
9863 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9864 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009865 CXXConstructorDecl *Constructor =
9866 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009867 // If this is a deleted function, add it anyway. This might be conformant
9868 // with the standard. This might not. I'm not sure. It might not matter.
9869 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009870 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009871 }
9872 }
9873
9874 // Field constructors.
9875 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9876 FEnd = ClassDecl->field_end();
9877 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009878 QualType FieldType = Context.getBaseElementType(F->getType());
9879 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9880 CXXConstructorDecl *Constructor =
9881 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009882 // If this is a deleted function, add it anyway. This might be conformant
9883 // with the standard. This might not. I'm not sure. It might not matter.
9884 // In particular, the problem is that this function never gets called. It
9885 // might just be ill-formed because this function attempts to refer to
9886 // a deleted function here.
9887 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009888 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009889 }
9890 }
9891
9892 return ExceptSpec;
9893}
9894
9895CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9896 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009897 // C++11 [class.copy]p9:
9898 // If the definition of a class X does not explicitly declare a move
9899 // constructor, one will be implicitly declared as defaulted if and only if:
9900 //
9901 // - [first 4 bullets]
9902 assert(ClassDecl->needsImplicitMoveConstructor());
9903
Richard Smithafb49182012-11-29 01:34:07 +00009904 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9905 if (DSM.isAlreadyBeingDeclared())
9906 return 0;
9907
Richard Smith1c931be2012-04-02 18:40:40 +00009908 // [Checked after we build the declaration]
9909 // - the move assignment operator would not be implicitly defined as
9910 // deleted,
9911
9912 // [DR1402]:
9913 // - each of X's non-static data members and direct or virtual base classes
9914 // has a type that either has a move constructor or is trivially copyable.
9915 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9916 ClassDecl->setFailedImplicitMoveConstructor();
9917 return 0;
9918 }
9919
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009920 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9921 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009922
Richard Smith7756afa2012-06-10 05:43:50 +00009923 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9924 CXXMoveConstructor,
9925 false);
9926
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009927 DeclarationName Name
9928 = Context.DeclarationNames.getCXXConstructorName(
9929 Context.getCanonicalType(ClassType));
9930 SourceLocation ClassLoc = ClassDecl->getLocation();
9931 DeclarationNameInfo NameInfo(Name, ClassLoc);
9932
Richard Smitha8942d72013-05-07 03:19:20 +00009933 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009934 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009935 // member of its class.
9936 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009937 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009938 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009939 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009940 MoveConstructor->setAccess(AS_public);
9941 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009942
Richard Smithb9d0b762012-07-27 04:22:15 +00009943 // Build an exception specification pointing back at this member.
9944 FunctionProtoType::ExtProtoInfo EPI;
9945 EPI.ExceptionSpecType = EST_Unevaluated;
9946 EPI.ExceptionSpecDecl = MoveConstructor;
9947 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009948 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009949
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009950 // Add the parameter to the constructor.
9951 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9952 ClassLoc, ClassLoc,
9953 /*IdentifierInfo=*/0,
9954 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009955 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009956 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009957
Richard Smithbc2a35d2012-12-08 08:32:28 +00009958 MoveConstructor->setTrivial(
9959 ClassDecl->needsOverloadResolutionForMoveConstructor()
9960 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9961 : ClassDecl->hasTrivialMoveConstructor());
9962
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009963 // C++0x [class.copy]p9:
9964 // If the definition of a class X does not explicitly declare a move
9965 // constructor, one will be implicitly declared as defaulted if and only if:
9966 // [...]
9967 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009968 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009969 // Cache this result so that we don't try to generate this over and over
9970 // on every lookup, leaking memory and wasting time.
9971 ClassDecl->setFailedImplicitMoveConstructor();
9972 return 0;
9973 }
9974
9975 // Note that we have declared this constructor.
9976 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9977
9978 if (Scope *S = getScopeForContext(ClassDecl))
9979 PushOnScopeChains(MoveConstructor, S, false);
9980 ClassDecl->addDecl(MoveConstructor);
9981
9982 return MoveConstructor;
9983}
9984
9985void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9986 CXXConstructorDecl *MoveConstructor) {
9987 assert((MoveConstructor->isDefaulted() &&
9988 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009989 !MoveConstructor->doesThisDeclarationHaveABody() &&
9990 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009991 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9992
9993 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9994 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9995
Eli Friedman9a14db32012-10-18 20:14:08 +00009996 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009997 DiagnosticErrorTrap Trap(Diags);
9998
David Blaikie93c86172013-01-17 05:26:25 +00009999 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010000 Trap.hasErrorOccurred()) {
10001 Diag(CurrentLocation, diag::note_member_synthesized_at)
10002 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10003 MoveConstructor->setInvalidDecl();
10004 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010005 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010006 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
10007 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010008 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010009 /*isStmtExpr=*/false)
10010 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +000010011 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010012 }
10013
10014 MoveConstructor->setUsed();
10015
10016 if (ASTMutationListener *L = getASTMutationListener()) {
10017 L->CompletedImplicitDefinition(MoveConstructor);
10018 }
10019}
10020
Douglas Gregore4e68d42012-02-15 19:33:52 +000010021bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010022 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010023}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010024
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010025/// \brief Mark the call operator of the given lambda closure type as "used".
10026static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10027 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010028 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010029 Lambda->lookup(
10030 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010031 CallOperator->setReferenced();
10032 CallOperator->setUsed();
10033}
10034
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010035void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10036 SourceLocation CurrentLocation,
10037 CXXConversionDecl *Conv)
10038{
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010039 CXXRecordDecl *Lambda = Conv->getParent();
10040
10041 // Make sure that the lambda call operator is marked used.
10042 markLambdaCallOperatorUsed(*this, Lambda);
10043
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010044 Conv->setUsed();
10045
Eli Friedman9a14db32012-10-18 20:14:08 +000010046 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010047 DiagnosticErrorTrap Trap(Diags);
10048
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010049 // Return the address of the __invoke function.
10050 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10051 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +000010052 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010053 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10054 VK_LValue, Conv->getLocation()).take();
10055 assert(FunctionRef && "Can't refer to __invoke function?");
10056 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010057 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010058 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010059 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010060
10061 // Fill in the __invoke function with a dummy implementation. IR generation
10062 // will fill in the actual details.
10063 Invoke->setUsed();
10064 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010065 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010066
10067 if (ASTMutationListener *L = getASTMutationListener()) {
10068 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010069 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010070 }
10071}
10072
10073void Sema::DefineImplicitLambdaToBlockPointerConversion(
10074 SourceLocation CurrentLocation,
10075 CXXConversionDecl *Conv)
10076{
10077 Conv->setUsed();
10078
Eli Friedman9a14db32012-10-18 20:14:08 +000010079 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010080 DiagnosticErrorTrap Trap(Diags);
10081
Douglas Gregorac1303e2012-02-22 05:02:47 +000010082 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010083 Expr *This = ActOnCXXThis(CurrentLocation).take();
10084 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010085
Eli Friedman23f02672012-03-01 04:01:32 +000010086 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10087 Conv->getLocation(),
10088 Conv, DerefThis);
10089
10090 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10091 // behavior. Note that only the general conversion function does this
10092 // (since it's unusable otherwise); in the case where we inline the
10093 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010094 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010095 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10096 CK_CopyAndAutoreleaseBlockObject,
10097 BuildBlock.get(), 0, VK_RValue);
10098
10099 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010100 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010101 Conv->setInvalidDecl();
10102 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010103 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010104
Douglas Gregorac1303e2012-02-22 05:02:47 +000010105 // Create the return statement that returns the block from the conversion
10106 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010107 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010108 if (Return.isInvalid()) {
10109 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10110 Conv->setInvalidDecl();
10111 return;
10112 }
10113
10114 // Set the body of the conversion function.
10115 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010116 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010117 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010118 Conv->getLocation()));
10119
Douglas Gregorac1303e2012-02-22 05:02:47 +000010120 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010121 if (ASTMutationListener *L = getASTMutationListener()) {
10122 L->CompletedImplicitDefinition(Conv);
10123 }
10124}
10125
Douglas Gregorf52757d2012-03-10 06:53:13 +000010126/// \brief Determine whether the given list arguments contains exactly one
10127/// "real" (non-default) argument.
10128static bool hasOneRealArgument(MultiExprArg Args) {
10129 switch (Args.size()) {
10130 case 0:
10131 return false;
10132
10133 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010134 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010135 return false;
10136
10137 // fall through
10138 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010139 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010140 }
10141
10142 return false;
10143}
10144
John McCall60d7b3a2010-08-24 06:29:42 +000010145ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010146Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010147 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010148 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010149 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010150 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010151 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010152 unsigned ConstructKind,
10153 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010154 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010155
Douglas Gregor2f599792010-04-02 18:24:57 +000010156 // C++0x [class.copy]p34:
10157 // When certain criteria are met, an implementation is allowed to
10158 // omit the copy/move construction of a class object, even if the
10159 // copy/move constructor and/or destructor for the object have
10160 // side effects. [...]
10161 // - when a temporary class object that has not been bound to a
10162 // reference (12.2) would be copied/moved to a class object
10163 // with the same cv-unqualified type, the copy/move operation
10164 // can be omitted by constructing the temporary object
10165 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010166 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010167 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010168 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010169 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010170 }
Mike Stump1eb44332009-09-09 15:08:12 +000010171
10172 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010173 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010174 IsListInitialization, RequiresZeroInit,
10175 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010176}
10177
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010178/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10179/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010180ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010181Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10182 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010183 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010184 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010185 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010186 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010187 unsigned ConstructKind,
10188 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010189 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010190 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010191 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010192 HadMultipleCandidates,
10193 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010194 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10195 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010196}
10197
John McCall68c6c9a2010-02-02 09:10:11 +000010198void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010199 if (VD->isInvalidDecl()) return;
10200
John McCall68c6c9a2010-02-02 09:10:11 +000010201 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010202 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010203 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010204 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010205
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010206 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010207 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010208 CheckDestructorAccess(VD->getLocation(), Destructor,
10209 PDiag(diag::err_access_dtor_var)
10210 << VD->getDeclName()
10211 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010212 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010213
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010214 if (!VD->hasGlobalStorage()) return;
10215
10216 // Emit warning for non-trivial dtor in global scope (a real global,
10217 // class-static, function-static).
10218 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10219
10220 // TODO: this should be re-enabled for static locals by !CXAAtExit
10221 if (!VD->isStaticLocal())
10222 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010223}
10224
Douglas Gregor39da0b82009-09-09 23:08:42 +000010225/// \brief Given a constructor and the set of arguments provided for the
10226/// constructor, convert the arguments and add any required default arguments
10227/// to form a proper call to this constructor.
10228///
10229/// \returns true if an error occurred, false otherwise.
10230bool
10231Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10232 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010233 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010234 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010235 bool AllowExplicit,
10236 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010237 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10238 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010239 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010240
10241 const FunctionProtoType *Proto
10242 = Constructor->getType()->getAs<FunctionProtoType>();
10243 assert(Proto && "Constructor without a prototype?");
10244 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010245
10246 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010247 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010248 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010249 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010250 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010251
10252 VariadicCallType CallType =
10253 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010254 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010255 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010256 Proto, 0,
10257 llvm::makeArrayRef(Args, NumArgs),
10258 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010259 CallType, AllowExplicit,
10260 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010261 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010262
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010263 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010264
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010265 CheckConstructorCall(Constructor,
10266 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10267 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010268 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010269
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010270 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010271}
10272
Anders Carlsson20d45d22009-12-12 00:32:00 +000010273static inline bool
10274CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10275 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010276 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010277 if (isa<NamespaceDecl>(DC)) {
10278 return SemaRef.Diag(FnDecl->getLocation(),
10279 diag::err_operator_new_delete_declared_in_namespace)
10280 << FnDecl->getDeclName();
10281 }
10282
10283 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010284 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010285 return SemaRef.Diag(FnDecl->getLocation(),
10286 diag::err_operator_new_delete_declared_static)
10287 << FnDecl->getDeclName();
10288 }
10289
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010290 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010291}
10292
Anders Carlsson156c78e2009-12-13 17:53:43 +000010293static inline bool
10294CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10295 CanQualType ExpectedResultType,
10296 CanQualType ExpectedFirstParamType,
10297 unsigned DependentParamTypeDiag,
10298 unsigned InvalidParamTypeDiag) {
10299 QualType ResultType =
10300 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10301
10302 // Check that the result type is not dependent.
10303 if (ResultType->isDependentType())
10304 return SemaRef.Diag(FnDecl->getLocation(),
10305 diag::err_operator_new_delete_dependent_result_type)
10306 << FnDecl->getDeclName() << ExpectedResultType;
10307
10308 // Check that the result type is what we expect.
10309 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10310 return SemaRef.Diag(FnDecl->getLocation(),
10311 diag::err_operator_new_delete_invalid_result_type)
10312 << FnDecl->getDeclName() << ExpectedResultType;
10313
10314 // A function template must have at least 2 parameters.
10315 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10316 return SemaRef.Diag(FnDecl->getLocation(),
10317 diag::err_operator_new_delete_template_too_few_parameters)
10318 << FnDecl->getDeclName();
10319
10320 // The function decl must have at least 1 parameter.
10321 if (FnDecl->getNumParams() == 0)
10322 return SemaRef.Diag(FnDecl->getLocation(),
10323 diag::err_operator_new_delete_too_few_parameters)
10324 << FnDecl->getDeclName();
10325
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010326 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010327 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10328 if (FirstParamType->isDependentType())
10329 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10330 << FnDecl->getDeclName() << ExpectedFirstParamType;
10331
10332 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010333 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010334 ExpectedFirstParamType)
10335 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10336 << FnDecl->getDeclName() << ExpectedFirstParamType;
10337
10338 return false;
10339}
10340
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010341static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010342CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010343 // C++ [basic.stc.dynamic.allocation]p1:
10344 // A program is ill-formed if an allocation function is declared in a
10345 // namespace scope other than global scope or declared static in global
10346 // scope.
10347 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10348 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010349
10350 CanQualType SizeTy =
10351 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10352
10353 // C++ [basic.stc.dynamic.allocation]p1:
10354 // The return type shall be void*. The first parameter shall have type
10355 // std::size_t.
10356 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10357 SizeTy,
10358 diag::err_operator_new_dependent_param_type,
10359 diag::err_operator_new_param_type))
10360 return true;
10361
10362 // C++ [basic.stc.dynamic.allocation]p1:
10363 // The first parameter shall not have an associated default argument.
10364 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010365 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010366 diag::err_operator_new_default_arg)
10367 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10368
10369 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010370}
10371
10372static bool
Richard Smith444d3842012-10-20 08:26:51 +000010373CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010374 // C++ [basic.stc.dynamic.deallocation]p1:
10375 // A program is ill-formed if deallocation functions are declared in a
10376 // namespace scope other than global scope or declared static in global
10377 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010378 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10379 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010380
10381 // C++ [basic.stc.dynamic.deallocation]p2:
10382 // Each deallocation function shall return void and its first parameter
10383 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010384 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10385 SemaRef.Context.VoidPtrTy,
10386 diag::err_operator_delete_dependent_param_type,
10387 diag::err_operator_delete_param_type))
10388 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010389
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010390 return false;
10391}
10392
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010393/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10394/// of this overloaded operator is well-formed. If so, returns false;
10395/// otherwise, emits appropriate diagnostics and returns true.
10396bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010397 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010398 "Expected an overloaded operator declaration");
10399
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010400 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10401
Mike Stump1eb44332009-09-09 15:08:12 +000010402 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010403 // The allocation and deallocation functions, operator new,
10404 // operator new[], operator delete and operator delete[], are
10405 // described completely in 3.7.3. The attributes and restrictions
10406 // found in the rest of this subclause do not apply to them unless
10407 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010408 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010409 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010410
Anders Carlssona3ccda52009-12-12 00:26:23 +000010411 if (Op == OO_New || Op == OO_Array_New)
10412 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010413
10414 // C++ [over.oper]p6:
10415 // An operator function shall either be a non-static member
10416 // function or be a non-member function and have at least one
10417 // parameter whose type is a class, a reference to a class, an
10418 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010419 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10420 if (MethodDecl->isStatic())
10421 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010422 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010423 } else {
10424 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010425 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10426 ParamEnd = FnDecl->param_end();
10427 Param != ParamEnd; ++Param) {
10428 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010429 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10430 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010431 ClassOrEnumParam = true;
10432 break;
10433 }
10434 }
10435
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010436 if (!ClassOrEnumParam)
10437 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010438 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010439 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010440 }
10441
10442 // C++ [over.oper]p8:
10443 // An operator function cannot have default arguments (8.3.6),
10444 // except where explicitly stated below.
10445 //
Mike Stump1eb44332009-09-09 15:08:12 +000010446 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010447 // (C++ [over.call]p1).
10448 if (Op != OO_Call) {
10449 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10450 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010451 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010452 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010453 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010454 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010455 }
10456 }
10457
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010458 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10459 { false, false, false }
10460#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10461 , { Unary, Binary, MemberOnly }
10462#include "clang/Basic/OperatorKinds.def"
10463 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010464
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010465 bool CanBeUnaryOperator = OperatorUses[Op][0];
10466 bool CanBeBinaryOperator = OperatorUses[Op][1];
10467 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010468
10469 // C++ [over.oper]p8:
10470 // [...] Operator functions cannot have more or fewer parameters
10471 // than the number required for the corresponding operator, as
10472 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010473 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010474 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010475 if (Op != OO_Call &&
10476 ((NumParams == 1 && !CanBeUnaryOperator) ||
10477 (NumParams == 2 && !CanBeBinaryOperator) ||
10478 (NumParams < 1) || (NumParams > 2))) {
10479 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010480 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010481 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010482 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010483 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010484 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010485 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010486 assert(CanBeBinaryOperator &&
10487 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010488 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010489 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010490
Chris Lattner416e46f2008-11-21 07:57:12 +000010491 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010492 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010493 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010494
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010495 // Overloaded operators other than operator() cannot be variadic.
10496 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010497 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010498 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010499 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010500 }
10501
10502 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010503 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10504 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010505 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010506 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010507 }
10508
10509 // C++ [over.inc]p1:
10510 // The user-defined function called operator++ implements the
10511 // prefix and postfix ++ operator. If this function is a member
10512 // function with no parameters, or a non-member function with one
10513 // parameter of class or enumeration type, it defines the prefix
10514 // increment operator ++ for objects of that type. If the function
10515 // is a member function with one parameter (which shall be of type
10516 // int) or a non-member function with two parameters (the second
10517 // of which shall be of type int), it defines the postfix
10518 // increment operator ++ for objects of that type.
10519 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10520 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10521 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010522 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010523 ParamIsInt = BT->getKind() == BuiltinType::Int;
10524
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010525 if (!ParamIsInt)
10526 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010527 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010528 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010529 }
10530
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010531 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010532}
Chris Lattner5a003a42008-12-17 07:09:26 +000010533
Sean Hunta6c058d2010-01-13 09:01:02 +000010534/// CheckLiteralOperatorDeclaration - Check whether the declaration
10535/// of this literal operator function is well-formed. If so, returns
10536/// false; otherwise, emits appropriate diagnostics and returns true.
10537bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010538 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010539 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10540 << FnDecl->getDeclName();
10541 return true;
10542 }
10543
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010544 if (FnDecl->isExternC()) {
10545 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10546 return true;
10547 }
10548
Sean Hunta6c058d2010-01-13 09:01:02 +000010549 bool Valid = false;
10550
Richard Smith36f5cfe2012-03-09 08:00:36 +000010551 // This might be the definition of a literal operator template.
10552 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10553 // This might be a specialization of a literal operator template.
10554 if (!TpDecl)
10555 TpDecl = FnDecl->getPrimaryTemplate();
10556
Sean Hunt216c2782010-04-07 23:11:06 +000010557 // template <char...> type operator "" name() is the only valid template
10558 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010559 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010560 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010561 // Must have only one template parameter
10562 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10563 if (Params->size() == 1) {
10564 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010565 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010566
Sean Hunt216c2782010-04-07 23:11:06 +000010567 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010568 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10569 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10570 Valid = true;
10571 }
10572 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010573 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010574 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010575 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10576
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010577 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010578
Sean Hunt30019c02010-04-07 22:57:35 +000010579 // unsigned long long int, long double, and any character type are allowed
10580 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010581 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10582 Context.hasSameType(T, Context.LongDoubleTy) ||
10583 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010584 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010585 Context.hasSameType(T, Context.Char16Ty) ||
10586 Context.hasSameType(T, Context.Char32Ty)) {
10587 if (++Param == FnDecl->param_end())
10588 Valid = true;
10589 goto FinishedParams;
10590 }
10591
Sean Hunt30019c02010-04-07 22:57:35 +000010592 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010593 const PointerType *PT = T->getAs<PointerType>();
10594 if (!PT)
10595 goto FinishedParams;
10596 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010597 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010598 goto FinishedParams;
10599 T = T.getUnqualifiedType();
10600
10601 // Move on to the second parameter;
10602 ++Param;
10603
10604 // If there is no second parameter, the first must be a const char *
10605 if (Param == FnDecl->param_end()) {
10606 if (Context.hasSameType(T, Context.CharTy))
10607 Valid = true;
10608 goto FinishedParams;
10609 }
10610
10611 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10612 // are allowed as the first parameter to a two-parameter function
10613 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010614 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010615 Context.hasSameType(T, Context.Char16Ty) ||
10616 Context.hasSameType(T, Context.Char32Ty)))
10617 goto FinishedParams;
10618
10619 // The second and final parameter must be an std::size_t
10620 T = (*Param)->getType().getUnqualifiedType();
10621 if (Context.hasSameType(T, Context.getSizeType()) &&
10622 ++Param == FnDecl->param_end())
10623 Valid = true;
10624 }
10625
10626 // FIXME: This diagnostic is absolutely terrible.
10627FinishedParams:
10628 if (!Valid) {
10629 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10630 << FnDecl->getDeclName();
10631 return true;
10632 }
10633
Richard Smitha9e88b22012-03-09 08:16:22 +000010634 // A parameter-declaration-clause containing a default argument is not
10635 // equivalent to any of the permitted forms.
10636 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10637 ParamEnd = FnDecl->param_end();
10638 Param != ParamEnd; ++Param) {
10639 if ((*Param)->hasDefaultArg()) {
10640 Diag((*Param)->getDefaultArgRange().getBegin(),
10641 diag::err_literal_operator_default_argument)
10642 << (*Param)->getDefaultArgRange();
10643 break;
10644 }
10645 }
10646
Richard Smith2fb4ae32012-03-08 02:39:21 +000010647 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010648 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10649 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010650 // C++11 [usrlit.suffix]p1:
10651 // Literal suffix identifiers that do not start with an underscore
10652 // are reserved for future standardization.
10653 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010654 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010655
Sean Hunta6c058d2010-01-13 09:01:02 +000010656 return false;
10657}
10658
Douglas Gregor074149e2009-01-05 19:45:36 +000010659/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10660/// linkage specification, including the language and (if present)
10661/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10662/// the location of the language string literal, which is provided
10663/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10664/// the '{' brace. Otherwise, this linkage specification does not
10665/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010666Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10667 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010668 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010669 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010670 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010671 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010672 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010673 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010674 Language = LinkageSpecDecl::lang_cxx;
10675 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010676 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010677 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010678 }
Mike Stump1eb44332009-09-09 15:08:12 +000010679
Chris Lattnercc98eac2008-12-17 07:13:27 +000010680 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010681
Douglas Gregor074149e2009-01-05 19:45:36 +000010682 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010683 ExternLoc, LangLoc, Language,
10684 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010685 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010686 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010687 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010688}
10689
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010690/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010691/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10692/// valid, it's the position of the closing '}' brace in a linkage
10693/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010694Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010695 Decl *LinkageSpec,
10696 SourceLocation RBraceLoc) {
10697 if (LinkageSpec) {
10698 if (RBraceLoc.isValid()) {
10699 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10700 LSDecl->setRBraceLoc(RBraceLoc);
10701 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010702 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010703 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010704 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010705}
10706
Michael Han684aa732013-02-22 17:15:32 +000010707Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10708 AttributeList *AttrList,
10709 SourceLocation SemiLoc) {
10710 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10711 // Attribute declarations appertain to empty declaration so we handle
10712 // them here.
10713 if (AttrList)
10714 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010715
Michael Han684aa732013-02-22 17:15:32 +000010716 CurContext->addDecl(ED);
10717 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010718}
10719
Douglas Gregord308e622009-05-18 20:51:54 +000010720/// \brief Perform semantic analysis for the variable declaration that
10721/// occurs within a C++ catch clause, returning the newly-created
10722/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010723VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010724 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010725 SourceLocation StartLoc,
10726 SourceLocation Loc,
10727 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010728 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010729 QualType ExDeclType = TInfo->getType();
10730
Sebastian Redl4b07b292008-12-22 19:15:10 +000010731 // Arrays and functions decay.
10732 if (ExDeclType->isArrayType())
10733 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10734 else if (ExDeclType->isFunctionType())
10735 ExDeclType = Context.getPointerType(ExDeclType);
10736
10737 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10738 // The exception-declaration shall not denote a pointer or reference to an
10739 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010740 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010741 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010742 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010743 Invalid = true;
10744 }
Douglas Gregord308e622009-05-18 20:51:54 +000010745
Sebastian Redl4b07b292008-12-22 19:15:10 +000010746 QualType BaseType = ExDeclType;
10747 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010748 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010749 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010750 BaseType = Ptr->getPointeeType();
10751 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010752 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010753 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010754 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010755 BaseType = Ref->getPointeeType();
10756 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010757 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010758 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010759 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010760 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010761 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010762
Mike Stump1eb44332009-09-09 15:08:12 +000010763 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010764 RequireNonAbstractType(Loc, ExDeclType,
10765 diag::err_abstract_type_in_decl,
10766 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010767 Invalid = true;
10768
John McCall5a180392010-07-24 00:37:23 +000010769 // Only the non-fragile NeXT runtime currently supports C++ catches
10770 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010771 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010772 QualType T = ExDeclType;
10773 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10774 T = RT->getPointeeType();
10775
10776 if (T->isObjCObjectType()) {
10777 Diag(Loc, diag::err_objc_object_catch);
10778 Invalid = true;
10779 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010780 // FIXME: should this be a test for macosx-fragile specifically?
10781 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010782 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010783 }
10784 }
10785
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010786 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010787 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010788 ExDecl->setExceptionVariable(true);
10789
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010790 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010791 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010792 Invalid = true;
10793
Douglas Gregorc41b8782011-07-06 18:14:43 +000010794 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010795 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010796 // Insulate this from anything else we might currently be parsing.
10797 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10798
Douglas Gregor6d182892010-03-05 23:38:39 +000010799 // C++ [except.handle]p16:
10800 // The object declared in an exception-declaration or, if the
10801 // exception-declaration does not specify a name, a temporary (12.2) is
10802 // copy-initialized (8.5) from the exception object. [...]
10803 // The object is destroyed when the handler exits, after the destruction
10804 // of any automatic objects initialized within the handler.
10805 //
10806 // We just pretend to initialize the object with itself, then make sure
10807 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010808 QualType initType = ExDeclType;
10809
10810 InitializedEntity entity =
10811 InitializedEntity::InitializeVariable(ExDecl);
10812 InitializationKind initKind =
10813 InitializationKind::CreateCopy(Loc, SourceLocation());
10814
10815 Expr *opaqueValue =
10816 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010817 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10818 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010819 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010820 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010821 else {
10822 // If the constructor used was non-trivial, set this as the
10823 // "initializer".
10824 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10825 if (!construct->getConstructor()->isTrivial()) {
10826 Expr *init = MaybeCreateExprWithCleanups(construct);
10827 ExDecl->setInit(init);
10828 }
10829
10830 // And make sure it's destructable.
10831 FinalizeVarWithDestructor(ExDecl, recordType);
10832 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010833 }
10834 }
10835
Douglas Gregord308e622009-05-18 20:51:54 +000010836 if (Invalid)
10837 ExDecl->setInvalidDecl();
10838
10839 return ExDecl;
10840}
10841
10842/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10843/// handler.
John McCalld226f652010-08-21 09:40:31 +000010844Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010845 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010846 bool Invalid = D.isInvalidType();
10847
10848 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010849 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10850 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010851 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10852 D.getIdentifierLoc());
10853 Invalid = true;
10854 }
10855
Sebastian Redl4b07b292008-12-22 19:15:10 +000010856 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010857 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010858 LookupOrdinaryName,
10859 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010860 // The scope should be freshly made just for us. There is just no way
10861 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010862 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010863 if (PrevDecl->isTemplateParameter()) {
10864 // Maybe we will complain about the shadowed template parameter.
10865 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010866 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010867 }
10868 }
10869
Chris Lattnereaaebc72009-04-25 08:06:05 +000010870 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010871 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10872 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010873 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010874 }
10875
Douglas Gregor83cb9422010-09-09 17:09:21 +000010876 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010877 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010878 D.getIdentifierLoc(),
10879 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010880 if (Invalid)
10881 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010882
Sebastian Redl4b07b292008-12-22 19:15:10 +000010883 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010884 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010885 PushOnScopeChains(ExDecl, S);
10886 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010887 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010888
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010889 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010890 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010891}
Anders Carlssonfb311762009-03-14 00:25:26 +000010892
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010893Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010894 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010895 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010896 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010897 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010898
Richard Smithe3f470a2012-07-11 22:37:56 +000010899 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10900 return 0;
10901
10902 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10903 AssertMessage, RParenLoc, false);
10904}
10905
10906Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10907 Expr *AssertExpr,
10908 StringLiteral *AssertMessage,
10909 SourceLocation RParenLoc,
10910 bool Failed) {
10911 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10912 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010913 // In a static_assert-declaration, the constant-expression shall be a
10914 // constant expression that can be contextually converted to bool.
10915 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10916 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010917 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010918
Richard Smithdaaefc52011-12-14 23:32:26 +000010919 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010920 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010921 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010922 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010923 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010924
Richard Smithe3f470a2012-07-11 22:37:56 +000010925 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010926 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010927 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010928 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010929 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010930 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010931 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010932 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010933 }
Mike Stump1eb44332009-09-09 15:08:12 +000010934
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010935 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010936 AssertExpr, AssertMessage, RParenLoc,
10937 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010938
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010939 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010940 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010941}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010942
Douglas Gregor1d869352010-04-07 16:53:43 +000010943/// \brief Perform semantic analysis of the given friend type declaration.
10944///
10945/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010946FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010947 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010948 TypeSourceInfo *TSInfo) {
10949 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10950
10951 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010952 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010953
Richard Smith6b130222011-10-18 21:39:00 +000010954 // C++03 [class.friend]p2:
10955 // An elaborated-type-specifier shall be used in a friend declaration
10956 // for a class.*
10957 //
10958 // * The class-key of the elaborated-type-specifier is required.
10959 if (!ActiveTemplateInstantiations.empty()) {
10960 // Do not complain about the form of friend template types during
10961 // template instantiation; we will already have complained when the
10962 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010963 } else {
10964 if (!T->isElaboratedTypeSpecifier()) {
10965 // If we evaluated the type to a record type, suggest putting
10966 // a tag in front.
10967 if (const RecordType *RT = T->getAs<RecordType>()) {
10968 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010969
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010970 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010971
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010972 Diag(TypeRange.getBegin(),
10973 getLangOpts().CPlusPlus11 ?
10974 diag::warn_cxx98_compat_unelaborated_friend_type :
10975 diag::ext_unelaborated_friend_type)
10976 << (unsigned) RD->getTagKind()
10977 << T
10978 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10979 InsertionText);
10980 } else {
10981 Diag(FriendLoc,
10982 getLangOpts().CPlusPlus11 ?
10983 diag::warn_cxx98_compat_nonclass_type_friend :
10984 diag::ext_nonclass_type_friend)
10985 << T
10986 << TypeRange;
10987 }
10988 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010989 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010990 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010991 diag::warn_cxx98_compat_enum_friend :
10992 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010993 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010994 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010995 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010996
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010997 // C++11 [class.friend]p3:
10998 // A friend declaration that does not declare a function shall have one
10999 // of the following forms:
11000 // friend elaborated-type-specifier ;
11001 // friend simple-type-specifier ;
11002 // friend typename-specifier ;
11003 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11004 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11005 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011006
Douglas Gregor06245bf2010-04-07 17:57:12 +000011007 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011008 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011009 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011010 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011011}
11012
John McCall9a34edb2010-10-19 01:40:49 +000011013/// Handle a friend tag declaration where the scope specifier was
11014/// templated.
11015Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11016 unsigned TagSpec, SourceLocation TagLoc,
11017 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011018 IdentifierInfo *Name,
11019 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011020 AttributeList *Attr,
11021 MultiTemplateParamsArg TempParamLists) {
11022 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11023
11024 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011025 bool Invalid = false;
11026
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011027 if (TemplateParameterList *TemplateParams =
11028 MatchTemplateParametersToScopeSpecifier(
11029 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11030 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011031 if (TemplateParams->size() > 0) {
11032 // This is a declaration of a class template.
11033 if (Invalid)
11034 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011035
Eric Christopher4110e132011-07-21 05:34:24 +000011036 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11037 SS, Name, NameLoc, Attr,
11038 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011039 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011040 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011041 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011042 } else {
11043 // The "template<>" header is extraneous.
11044 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11045 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11046 isExplicitSpecialization = true;
11047 }
11048 }
11049
11050 if (Invalid) return 0;
11051
John McCall9a34edb2010-10-19 01:40:49 +000011052 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011053 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011054 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011055 isAllExplicitSpecializations = false;
11056 break;
11057 }
11058 }
11059
11060 // FIXME: don't ignore attributes.
11061
11062 // If it's explicit specializations all the way down, just forget
11063 // about the template header and build an appropriate non-templated
11064 // friend. TODO: for source fidelity, remember the headers.
11065 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011066 if (SS.isEmpty()) {
11067 bool Owned = false;
11068 bool IsDependent = false;
11069 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11070 Attr, AS_public,
11071 /*ModulePrivateLoc=*/SourceLocation(),
11072 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011073 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011074 /*ScopedEnumUsesClassTag=*/false,
11075 /*UnderlyingType=*/TypeResult());
11076 }
11077
Douglas Gregor2494dd02011-03-01 01:34:45 +000011078 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011079 ElaboratedTypeKeyword Keyword
11080 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011081 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011082 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011083 if (T.isNull())
11084 return 0;
11085
11086 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11087 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011088 DependentNameTypeLoc TL =
11089 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011090 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011091 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011092 TL.setNameLoc(NameLoc);
11093 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011094 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011095 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011096 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011097 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011098 }
11099
11100 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011101 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011102 Friend->setAccess(AS_public);
11103 CurContext->addDecl(Friend);
11104 return Friend;
11105 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011106
11107 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11108
11109
John McCall9a34edb2010-10-19 01:40:49 +000011110
11111 // Handle the case of a templated-scope friend class. e.g.
11112 // template <class T> class A<T>::B;
11113 // FIXME: we don't support these right now.
11114 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11115 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11116 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011117 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011118 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011119 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011120 TL.setNameLoc(NameLoc);
11121
11122 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011123 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011124 Friend->setAccess(AS_public);
11125 Friend->setUnsupportedFriend(true);
11126 CurContext->addDecl(Friend);
11127 return Friend;
11128}
11129
11130
John McCalldd4a3b02009-09-16 22:47:08 +000011131/// Handle a friend type declaration. This works in tandem with
11132/// ActOnTag.
11133///
11134/// Notes on friend class templates:
11135///
11136/// We generally treat friend class declarations as if they were
11137/// declaring a class. So, for example, the elaborated type specifier
11138/// in a friend declaration is required to obey the restrictions of a
11139/// class-head (i.e. no typedefs in the scope chain), template
11140/// parameters are required to match up with simple template-ids, &c.
11141/// However, unlike when declaring a template specialization, it's
11142/// okay to refer to a template specialization without an empty
11143/// template parameter declaration, e.g.
11144/// friend class A<T>::B<unsigned>;
11145/// We permit this as a special case; if there are any template
11146/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011147/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011148Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011149 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011150 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011151
11152 assert(DS.isFriendSpecified());
11153 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11154
John McCalldd4a3b02009-09-16 22:47:08 +000011155 // Try to convert the decl specifier to a type. This works for
11156 // friend templates because ActOnTag never produces a ClassTemplateDecl
11157 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011158 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011159 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11160 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011161 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011162 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011163
Douglas Gregor6ccab972010-12-16 01:14:37 +000011164 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11165 return 0;
11166
John McCalldd4a3b02009-09-16 22:47:08 +000011167 // This is definitely an error in C++98. It's probably meant to
11168 // be forbidden in C++0x, too, but the specification is just
11169 // poorly written.
11170 //
11171 // The problem is with declarations like the following:
11172 // template <T> friend A<T>::foo;
11173 // where deciding whether a class C is a friend or not now hinges
11174 // on whether there exists an instantiation of A that causes
11175 // 'foo' to equal C. There are restrictions on class-heads
11176 // (which we declare (by fiat) elaborated friend declarations to
11177 // be) that makes this tractable.
11178 //
11179 // FIXME: handle "template <> friend class A<T>;", which
11180 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011181 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011182 Diag(Loc, diag::err_tagless_friend_type_template)
11183 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011184 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011185 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011186
John McCall02cace72009-08-28 07:59:38 +000011187 // C++98 [class.friend]p1: A friend of a class is a function
11188 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011189 // This is fixed in DR77, which just barely didn't make the C++03
11190 // deadline. It's also a very silly restriction that seriously
11191 // affects inner classes and which nobody else seems to implement;
11192 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011193 //
11194 // But note that we could warn about it: it's always useless to
11195 // friend one of your own members (it's not, however, worthless to
11196 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011197
John McCalldd4a3b02009-09-16 22:47:08 +000011198 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011199 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011200 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011201 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011202 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011203 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011204 DS.getFriendSpecLoc());
11205 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011206 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011207
11208 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011209 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011210
John McCalldd4a3b02009-09-16 22:47:08 +000011211 D->setAccess(AS_public);
11212 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011213
John McCalld226f652010-08-21 09:40:31 +000011214 return D;
John McCall02cace72009-08-28 07:59:38 +000011215}
11216
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011217NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11218 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011219 const DeclSpec &DS = D.getDeclSpec();
11220
11221 assert(DS.isFriendSpecified());
11222 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11223
11224 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011225 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011226
11227 // C++ [class.friend]p1
11228 // A friend of a class is a function or class....
11229 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011230 // It *doesn't* see through dependent types, which is correct
11231 // according to [temp.arg.type]p3:
11232 // If a declaration acquires a function type through a
11233 // type dependent on a template-parameter and this causes
11234 // a declaration that does not use the syntactic form of a
11235 // function declarator to have a function type, the program
11236 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011237 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011238 Diag(Loc, diag::err_unexpected_friend);
11239
11240 // It might be worthwhile to try to recover by creating an
11241 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011242 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011243 }
11244
11245 // C++ [namespace.memdef]p3
11246 // - If a friend declaration in a non-local class first declares a
11247 // class or function, the friend class or function is a member
11248 // of the innermost enclosing namespace.
11249 // - The name of the friend is not found by simple name lookup
11250 // until a matching declaration is provided in that namespace
11251 // scope (either before or after the class declaration granting
11252 // friendship).
11253 // - If a friend function is called, its name may be found by the
11254 // name lookup that considers functions from namespaces and
11255 // classes associated with the types of the function arguments.
11256 // - When looking for a prior declaration of a class or a function
11257 // declared as a friend, scopes outside the innermost enclosing
11258 // namespace scope are not considered.
11259
John McCall337ec3d2010-10-12 23:13:28 +000011260 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011261 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11262 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011263 assert(Name);
11264
Douglas Gregor6ccab972010-12-16 01:14:37 +000011265 // Check for unexpanded parameter packs.
11266 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11267 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11268 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11269 return 0;
11270
John McCall67d1a672009-08-06 02:15:43 +000011271 // The context we found the declaration in, or in which we should
11272 // create the declaration.
11273 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011274 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011275 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011276 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011277
John McCall337ec3d2010-10-12 23:13:28 +000011278 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011279
John McCall337ec3d2010-10-12 23:13:28 +000011280 // There are four cases here.
11281 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011282 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011283 // there as appropriate.
11284 // Recover from invalid scope qualifiers as if they just weren't there.
11285 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011286 // C++0x [namespace.memdef]p3:
11287 // If the name in a friend declaration is neither qualified nor
11288 // a template-id and the declaration is a function or an
11289 // elaborated-type-specifier, the lookup to determine whether
11290 // the entity has been previously declared shall not consider
11291 // any scopes outside the innermost enclosing namespace.
11292 // C++0x [class.friend]p11:
11293 // If a friend declaration appears in a local class and the name
11294 // specified is an unqualified name, a prior declaration is
11295 // looked up without considering scopes that are outside the
11296 // innermost enclosing non-class scope. For a friend function
11297 // declaration, if there is no prior declaration, the program is
11298 // ill-formed.
11299 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011300 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011301
John McCall29ae6e52010-10-13 05:45:15 +000011302 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011303 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011304
Rafael Espindola11dc6342013-04-25 20:12:36 +000011305 // Skip class contexts. If someone can cite chapter and verse
11306 // for this behavior, that would be nice --- it's what GCC and
11307 // EDG do, and it seems like a reasonable intent, but the spec
11308 // really only says that checks for unqualified existing
11309 // declarations should stop at the nearest enclosing namespace,
11310 // not that they should only consider the nearest enclosing
11311 // namespace.
11312 while (DC->isRecord())
11313 DC = DC->getParent();
11314
11315 DeclContext *LookupDC = DC;
11316 while (LookupDC->isTransparentContext())
11317 LookupDC = LookupDC->getParent();
11318
11319 while (true) {
11320 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011321
11322 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011323 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011324 break;
John McCall29ae6e52010-10-13 05:45:15 +000011325
Rafael Espindola11dc6342013-04-25 20:12:36 +000011326 if (!Previous.empty()) {
11327 DC = LookupDC;
11328 break;
John McCall8a407372010-10-14 22:22:28 +000011329 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011330
11331 if (isTemplateId) {
11332 if (isa<TranslationUnitDecl>(LookupDC)) break;
11333 } else {
11334 if (LookupDC->isFileContext()) break;
11335 }
11336 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011337 }
11338
John McCall380aaa42010-10-13 06:22:15 +000011339 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011340
Douglas Gregor883af832011-10-10 01:11:59 +000011341 // C++ [class.friend]p6:
11342 // A function can be defined in a friend declaration of a class if and
11343 // only if the class is a non-local class (9.8), the function name is
11344 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011345 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011346 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11347 }
11348
John McCall337ec3d2010-10-12 23:13:28 +000011349 // - There's a non-dependent scope specifier, in which case we
11350 // compute it and do a previous lookup there for a function
11351 // or function template.
11352 } else if (!SS.getScopeRep()->isDependent()) {
11353 DC = computeDeclContext(SS);
11354 if (!DC) return 0;
11355
11356 if (RequireCompleteDeclContext(SS, DC)) return 0;
11357
11358 LookupQualifiedName(Previous, DC);
11359
11360 // Ignore things found implicitly in the wrong scope.
11361 // TODO: better diagnostics for this case. Suggesting the right
11362 // qualified scope would be nice...
11363 LookupResult::Filter F = Previous.makeFilter();
11364 while (F.hasNext()) {
11365 NamedDecl *D = F.next();
11366 if (!DC->InEnclosingNamespaceSetOf(
11367 D->getDeclContext()->getRedeclContext()))
11368 F.erase();
11369 }
11370 F.done();
11371
11372 if (Previous.empty()) {
11373 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011374 Diag(Loc, diag::err_qualified_friend_not_found)
11375 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011376 return 0;
11377 }
11378
11379 // C++ [class.friend]p1: A friend of a class is a function or
11380 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011381 if (DC->Equals(CurContext))
11382 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011383 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011384 diag::warn_cxx98_compat_friend_is_member :
11385 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011386
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011387 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011388 // C++ [class.friend]p6:
11389 // A function can be defined in a friend declaration of a class if and
11390 // only if the class is a non-local class (9.8), the function name is
11391 // unqualified, and the function has namespace scope.
11392 SemaDiagnosticBuilder DB
11393 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11394
11395 DB << SS.getScopeRep();
11396 if (DC->isFileContext())
11397 DB << FixItHint::CreateRemoval(SS.getRange());
11398 SS.clear();
11399 }
John McCall337ec3d2010-10-12 23:13:28 +000011400
11401 // - There's a scope specifier that does not match any template
11402 // parameter lists, in which case we use some arbitrary context,
11403 // create a method or method template, and wait for instantiation.
11404 // - There's a scope specifier that does match some template
11405 // parameter lists, which we don't handle right now.
11406 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011407 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011408 // C++ [class.friend]p6:
11409 // A function can be defined in a friend declaration of a class if and
11410 // only if the class is a non-local class (9.8), the function name is
11411 // unqualified, and the function has namespace scope.
11412 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11413 << SS.getScopeRep();
11414 }
11415
John McCall337ec3d2010-10-12 23:13:28 +000011416 DC = CurContext;
11417 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011418 }
Douglas Gregor883af832011-10-10 01:11:59 +000011419
John McCall29ae6e52010-10-13 05:45:15 +000011420 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011421 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011422 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11423 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11424 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011425 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011426 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11427 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011428 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011429 }
John McCall67d1a672009-08-06 02:15:43 +000011430 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011431
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011432 // FIXME: This is an egregious hack to cope with cases where the scope stack
11433 // does not contain the declaration context, i.e., in an out-of-line
11434 // definition of a class.
11435 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11436 if (!DCScope) {
11437 FakeDCScope.setEntity(DC);
11438 DCScope = &FakeDCScope;
11439 }
11440
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011441 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011442 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011443 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011444 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011445
Douglas Gregor182ddf02009-09-28 00:08:27 +000011446 assert(ND->getDeclContext() == DC);
11447 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011448
John McCallab88d972009-08-31 22:39:49 +000011449 // Add the function declaration to the appropriate lookup tables,
11450 // adjusting the redeclarations list as necessary. We don't
11451 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011452 //
John McCallab88d972009-08-31 22:39:49 +000011453 // Also update the scope-based lookup if the target context's
11454 // lookup context is in lexical scope.
11455 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011456 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011457 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011458 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011459 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011460 }
John McCall02cace72009-08-28 07:59:38 +000011461
11462 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011463 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011464 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011465 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011466 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011467
John McCall1f2e1a92012-08-10 03:15:35 +000011468 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011469 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011470 } else {
11471 if (DC->isRecord()) CheckFriendAccess(ND);
11472
John McCall6102ca12010-10-16 06:59:13 +000011473 FunctionDecl *FD;
11474 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11475 FD = FTD->getTemplatedDecl();
11476 else
11477 FD = cast<FunctionDecl>(ND);
11478
David Majnemerf6a144f2013-06-25 23:09:30 +000011479 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11480 // default argument expression, that declaration shall be a definition
11481 // and shall be the only declaration of the function or function
11482 // template in the translation unit.
11483 if (functionDeclHasDefaultArgument(FD)) {
11484 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11485 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11486 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11487 } else if (!D.isFunctionDefinition())
11488 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11489 }
11490
John McCall6102ca12010-10-16 06:59:13 +000011491 // Mark templated-scope function declarations as unsupported.
11492 if (FD->getNumTemplateParameterLists())
11493 FrD->setUnsupportedFriend(true);
11494 }
John McCall337ec3d2010-10-12 23:13:28 +000011495
John McCalld226f652010-08-21 09:40:31 +000011496 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011497}
11498
John McCalld226f652010-08-21 09:40:31 +000011499void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11500 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011501
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011502 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011503 if (!Fn) {
11504 Diag(DelLoc, diag::err_deleted_non_function);
11505 return;
11506 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011507
Douglas Gregoref96ee02012-01-14 16:38:05 +000011508 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011509 // Don't consider the implicit declaration we generate for explicit
11510 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011511 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11512 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011513 Diag(DelLoc, diag::err_deleted_decl_not_first);
11514 Diag(Prev->getLocation(), diag::note_previous_declaration);
11515 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011516 // If the declaration wasn't the first, we delete the function anyway for
11517 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011518 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011519 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011520
11521 if (Fn->isDeleted())
11522 return;
11523
11524 // See if we're deleting a function which is already known to override a
11525 // non-deleted virtual function.
11526 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11527 bool IssuedDiagnostic = false;
11528 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11529 E = MD->end_overridden_methods();
11530 I != E; ++I) {
11531 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11532 if (!IssuedDiagnostic) {
11533 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11534 IssuedDiagnostic = true;
11535 }
11536 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11537 }
11538 }
11539 }
11540
Sean Hunt10620eb2011-05-06 20:44:56 +000011541 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011542}
Sebastian Redl13e88542009-04-27 21:33:24 +000011543
Sean Hunte4246a62011-05-12 06:15:49 +000011544void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011545 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011546
11547 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011548 if (MD->getParent()->isDependentType()) {
11549 MD->setDefaulted();
11550 MD->setExplicitlyDefaulted();
11551 return;
11552 }
11553
Sean Hunte4246a62011-05-12 06:15:49 +000011554 CXXSpecialMember Member = getSpecialMember(MD);
11555 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011556 if (!MD->isInvalidDecl())
11557 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011558 return;
11559 }
11560
11561 MD->setDefaulted();
11562 MD->setExplicitlyDefaulted();
11563
Sean Huntcd10dec2011-05-23 23:14:04 +000011564 // If this definition appears within the record, do the checking when
11565 // the record is complete.
11566 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011567 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011568 // Find the uninstantiated declaration that actually had the '= default'
11569 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011570 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011571
Richard Smith12fef492013-03-27 00:22:47 +000011572 // If the method was defaulted on its first declaration, we will have
11573 // already performed the checking in CheckCompletedCXXClass. Such a
11574 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011575 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011576 return;
11577
Richard Smithb9d0b762012-07-27 04:22:15 +000011578 CheckExplicitlyDefaultedSpecialMember(MD);
11579
Richard Smith1d28caf2012-12-11 01:14:52 +000011580 // The exception specification is needed because we are defining the
11581 // function.
11582 ResolveExceptionSpec(DefaultLoc,
11583 MD->getType()->castAs<FunctionProtoType>());
11584
Sean Hunte4246a62011-05-12 06:15:49 +000011585 switch (Member) {
11586 case CXXDefaultConstructor: {
11587 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011588 if (!CD->isInvalidDecl())
11589 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11590 break;
11591 }
11592
11593 case CXXCopyConstructor: {
11594 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011595 if (!CD->isInvalidDecl())
11596 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011597 break;
11598 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011599
Sean Hunt2b188082011-05-14 05:23:28 +000011600 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011601 if (!MD->isInvalidDecl())
11602 DefineImplicitCopyAssignment(DefaultLoc, MD);
11603 break;
11604 }
11605
Sean Huntcb45a0f2011-05-12 22:46:25 +000011606 case CXXDestructor: {
11607 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011608 if (!DD->isInvalidDecl())
11609 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011610 break;
11611 }
11612
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011613 case CXXMoveConstructor: {
11614 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011615 if (!CD->isInvalidDecl())
11616 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011617 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011618 }
Sean Hunt82713172011-05-25 23:16:36 +000011619
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011620 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011621 if (!MD->isInvalidDecl())
11622 DefineImplicitMoveAssignment(DefaultLoc, MD);
11623 break;
11624 }
11625
11626 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011627 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011628 }
11629 } else {
11630 Diag(DefaultLoc, diag::err_default_special_members);
11631 }
11632}
11633
Sebastian Redl13e88542009-04-27 21:33:24 +000011634static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011635 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011636 Stmt *SubStmt = *CI;
11637 if (!SubStmt)
11638 continue;
11639 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011640 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011641 diag::err_return_in_constructor_handler);
11642 if (!isa<Expr>(SubStmt))
11643 SearchForReturnInStmt(Self, SubStmt);
11644 }
11645}
11646
11647void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11648 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11649 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11650 SearchForReturnInStmt(*this, Handler);
11651 }
11652}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011653
David Blaikie299adab2013-01-18 23:03:15 +000011654bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011655 const CXXMethodDecl *Old) {
11656 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11657 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11658
11659 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11660
11661 // If the calling conventions match, everything is fine
11662 if (NewCC == OldCC)
11663 return false;
11664
11665 // If either of the calling conventions are set to "default", we need to pick
11666 // something more sensible based on the target. This supports code where the
11667 // one method explicitly sets thiscall, and another has no explicit calling
11668 // convention.
11669 CallingConv Default =
11670 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11671 if (NewCC == CC_Default)
11672 NewCC = Default;
11673 if (OldCC == CC_Default)
11674 OldCC = Default;
11675
11676 // If the calling conventions still don't match, then report the error
11677 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011678 Diag(New->getLocation(),
11679 diag::err_conflicting_overriding_cc_attributes)
11680 << New->getDeclName() << New->getType() << Old->getType();
11681 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11682 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011683 }
11684
11685 return false;
11686}
11687
Mike Stump1eb44332009-09-09 15:08:12 +000011688bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011689 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011690 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11691 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011692
Chandler Carruth73857792010-02-15 11:53:20 +000011693 if (Context.hasSameType(NewTy, OldTy) ||
11694 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011695 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011696
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011697 // Check if the return types are covariant
11698 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011699
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011700 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011701 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11702 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011703 NewClassTy = NewPT->getPointeeType();
11704 OldClassTy = OldPT->getPointeeType();
11705 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011706 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11707 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11708 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11709 NewClassTy = NewRT->getPointeeType();
11710 OldClassTy = OldRT->getPointeeType();
11711 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011712 }
11713 }
Mike Stump1eb44332009-09-09 15:08:12 +000011714
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011715 // The return types aren't either both pointers or references to a class type.
11716 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011717 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011718 diag::err_different_return_type_for_overriding_virtual_function)
11719 << New->getDeclName() << NewTy << OldTy;
11720 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011721
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011722 return true;
11723 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011724
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011725 // C++ [class.virtual]p6:
11726 // If the return type of D::f differs from the return type of B::f, the
11727 // class type in the return type of D::f shall be complete at the point of
11728 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011729 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11730 if (!RT->isBeingDefined() &&
11731 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011732 diag::err_covariant_return_incomplete,
11733 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011734 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011735 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011736
Douglas Gregora4923eb2009-11-16 21:35:15 +000011737 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011738 // Check if the new class derives from the old class.
11739 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11740 Diag(New->getLocation(),
11741 diag::err_covariant_return_not_derived)
11742 << New->getDeclName() << NewTy << OldTy;
11743 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11744 return true;
11745 }
Mike Stump1eb44332009-09-09 15:08:12 +000011746
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011747 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011748 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011749 diag::err_covariant_return_inaccessible_base,
11750 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11751 // FIXME: Should this point to the return type?
11752 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011753 // FIXME: this note won't trigger for delayed access control
11754 // diagnostics, and it's impossible to get an undelayed error
11755 // here from access control during the original parse because
11756 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011757 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11758 return true;
11759 }
11760 }
Mike Stump1eb44332009-09-09 15:08:12 +000011761
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011762 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011763 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011764 Diag(New->getLocation(),
11765 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011766 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011767 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11768 return true;
11769 };
Mike Stump1eb44332009-09-09 15:08:12 +000011770
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011771
11772 // The new class type must have the same or less qualifiers as the old type.
11773 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11774 Diag(New->getLocation(),
11775 diag::err_covariant_return_type_class_type_more_qualified)
11776 << New->getDeclName() << NewTy << OldTy;
11777 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11778 return true;
11779 };
Mike Stump1eb44332009-09-09 15:08:12 +000011780
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011781 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011782}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011783
Douglas Gregor4ba31362009-12-01 17:24:26 +000011784/// \brief Mark the given method pure.
11785///
11786/// \param Method the method to be marked pure.
11787///
11788/// \param InitRange the source range that covers the "0" initializer.
11789bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011790 SourceLocation EndLoc = InitRange.getEnd();
11791 if (EndLoc.isValid())
11792 Method->setRangeEnd(EndLoc);
11793
Douglas Gregor4ba31362009-12-01 17:24:26 +000011794 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11795 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011796 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011797 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011798
11799 if (!Method->isInvalidDecl())
11800 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11801 << Method->getDeclName() << InitRange;
11802 return true;
11803}
11804
Douglas Gregor552e2992012-02-21 02:22:07 +000011805/// \brief Determine whether the given declaration is a static data member.
11806static bool isStaticDataMember(Decl *D) {
11807 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11808 if (!Var)
11809 return false;
11810
11811 return Var->isStaticDataMember();
11812}
John McCall731ad842009-12-19 09:28:58 +000011813/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11814/// an initializer for the out-of-line declaration 'Dcl'. The scope
11815/// is a fresh scope pushed for just this purpose.
11816///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011817/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11818/// static data member of class X, names should be looked up in the scope of
11819/// class X.
John McCalld226f652010-08-21 09:40:31 +000011820void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011821 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011822 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011823
John McCall731ad842009-12-19 09:28:58 +000011824 // We should only get called for declarations with scope specifiers, like:
11825 // int foo::bar;
11826 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011827 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011828
11829 // If we are parsing the initializer for a static data member, push a
11830 // new expression evaluation context that is associated with this static
11831 // data member.
11832 if (isStaticDataMember(D))
11833 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011834}
11835
11836/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011837/// initializer for the out-of-line declaration 'D'.
11838void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011839 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011840 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011841
Douglas Gregor552e2992012-02-21 02:22:07 +000011842 if (isStaticDataMember(D))
11843 PopExpressionEvaluationContext();
11844
John McCall731ad842009-12-19 09:28:58 +000011845 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011846 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011847}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011848
11849/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11850/// C++ if/switch/while/for statement.
11851/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011852DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011853 // C++ 6.4p2:
11854 // The declarator shall not specify a function or an array.
11855 // The type-specifier-seq shall not contain typedef and shall not declare a
11856 // new class or enumeration.
11857 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11858 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011859
11860 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011861 if (!Dcl)
11862 return true;
11863
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011864 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11865 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011866 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011867 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011868 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011869
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011870 return Dcl;
11871}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011872
Douglas Gregordfe65432011-07-28 19:11:31 +000011873void Sema::LoadExternalVTableUses() {
11874 if (!ExternalSource)
11875 return;
11876
11877 SmallVector<ExternalVTableUse, 4> VTables;
11878 ExternalSource->ReadUsedVTables(VTables);
11879 SmallVector<VTableUse, 4> NewUses;
11880 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11881 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11882 = VTablesUsed.find(VTables[I].Record);
11883 // Even if a definition wasn't required before, it may be required now.
11884 if (Pos != VTablesUsed.end()) {
11885 if (!Pos->second && VTables[I].DefinitionRequired)
11886 Pos->second = true;
11887 continue;
11888 }
11889
11890 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11891 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11892 }
11893
11894 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11895}
11896
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011897void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11898 bool DefinitionRequired) {
11899 // Ignore any vtable uses in unevaluated operands or for classes that do
11900 // not have a vtable.
11901 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011902 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011903 return;
11904
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011905 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011906 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011907 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11908 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11909 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11910 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011911 // If we already had an entry, check to see if we are promoting this vtable
11912 // to required a definition. If so, we need to reappend to the VTableUses
11913 // list, since we may have already processed the first entry.
11914 if (DefinitionRequired && !Pos.first->second) {
11915 Pos.first->second = true;
11916 } else {
11917 // Otherwise, we can early exit.
11918 return;
11919 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011920 }
11921
11922 // Local classes need to have their virtual members marked
11923 // immediately. For all other classes, we mark their virtual members
11924 // at the end of the translation unit.
11925 if (Class->isLocalClass())
11926 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011927 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011928 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011929}
11930
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011931bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011932 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011933 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011934 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011935
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011936 // Note: The VTableUses vector could grow as a result of marking
11937 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011938 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011939 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011940 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011941 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011942 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011943 if (!Class)
11944 continue;
11945
11946 SourceLocation Loc = VTableUses[I].second;
11947
Richard Smithb9d0b762012-07-27 04:22:15 +000011948 bool DefineVTable = true;
11949
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011950 // If this class has a key function, but that key function is
11951 // defined in another translation unit, we don't need to emit the
11952 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011953 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011954 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011955 switch (KeyFunction->getTemplateSpecializationKind()) {
11956 case TSK_Undeclared:
11957 case TSK_ExplicitSpecialization:
11958 case TSK_ExplicitInstantiationDeclaration:
11959 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011960 DefineVTable = false;
11961 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011962
11963 case TSK_ExplicitInstantiationDefinition:
11964 case TSK_ImplicitInstantiation:
11965 // We will be instantiating the key function.
11966 break;
11967 }
11968 } else if (!KeyFunction) {
11969 // If we have a class with no key function that is the subject
11970 // of an explicit instantiation declaration, suppress the
11971 // vtable; it will live with the explicit instantiation
11972 // definition.
11973 bool IsExplicitInstantiationDeclaration
11974 = Class->getTemplateSpecializationKind()
11975 == TSK_ExplicitInstantiationDeclaration;
11976 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11977 REnd = Class->redecls_end();
11978 R != REnd; ++R) {
11979 TemplateSpecializationKind TSK
11980 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11981 if (TSK == TSK_ExplicitInstantiationDeclaration)
11982 IsExplicitInstantiationDeclaration = true;
11983 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11984 IsExplicitInstantiationDeclaration = false;
11985 break;
11986 }
11987 }
11988
11989 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011990 DefineVTable = false;
11991 }
11992
11993 // The exception specifications for all virtual members may be needed even
11994 // if we are not providing an authoritative form of the vtable in this TU.
11995 // We may choose to emit it available_externally anyway.
11996 if (!DefineVTable) {
11997 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11998 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011999 }
12000
12001 // Mark all of the virtual members of this class as referenced, so
12002 // that we can build a vtable. Then, tell the AST consumer that a
12003 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012004 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012005 MarkVirtualMembersReferenced(Loc, Class);
12006 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12007 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12008
12009 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012010 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012011 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012012 const FunctionDecl *KeyFunctionDef = 0;
12013 if (!KeyFunction ||
12014 (KeyFunction->hasBody(KeyFunctionDef) &&
12015 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012016 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12017 TSK_ExplicitInstantiationDefinition
12018 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12019 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012020 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012021 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012022 VTableUses.clear();
12023
Douglas Gregor78844032011-04-22 22:25:37 +000012024 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012025}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012026
Richard Smithb9d0b762012-07-27 04:22:15 +000012027void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12028 const CXXRecordDecl *RD) {
12029 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12030 E = RD->method_end(); I != E; ++I)
12031 if ((*I)->isVirtual() && !(*I)->isPure())
12032 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12033}
12034
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012035void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12036 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012037 // Mark all functions which will appear in RD's vtable as used.
12038 CXXFinalOverriderMap FinalOverriders;
12039 RD->getFinalOverriders(FinalOverriders);
12040 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12041 E = FinalOverriders.end();
12042 I != E; ++I) {
12043 for (OverridingMethods::const_iterator OI = I->second.begin(),
12044 OE = I->second.end();
12045 OI != OE; ++OI) {
12046 assert(OI->second.size() > 0 && "no final overrider");
12047 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012048
Richard Smithff817f72012-07-07 06:59:51 +000012049 // C++ [basic.def.odr]p2:
12050 // [...] A virtual member function is used if it is not pure. [...]
12051 if (!Overrider->isPure())
12052 MarkFunctionReferenced(Loc, Overrider);
12053 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012054 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012055
12056 // Only classes that have virtual bases need a VTT.
12057 if (RD->getNumVBases() == 0)
12058 return;
12059
12060 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12061 e = RD->bases_end(); i != e; ++i) {
12062 const CXXRecordDecl *Base =
12063 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012064 if (Base->getNumVBases() == 0)
12065 continue;
12066 MarkVirtualMembersReferenced(Loc, Base);
12067 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012068}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012069
12070/// SetIvarInitializers - This routine builds initialization ASTs for the
12071/// Objective-C implementation whose ivars need be initialized.
12072void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012073 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012074 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012075 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012076 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012077 CollectIvarsToConstructOrDestruct(OID, ivars);
12078 if (ivars.empty())
12079 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012080 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012081 for (unsigned i = 0; i < ivars.size(); i++) {
12082 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012083 if (Field->isInvalidDecl())
12084 continue;
12085
Sean Huntcbb67482011-01-08 20:30:50 +000012086 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012087 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12088 InitializationKind InitKind =
12089 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012090
12091 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12092 ExprResult MemberInit =
12093 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012094 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012095 // Note, MemberInit could actually come back empty if no initialization
12096 // is required (e.g., because it would call a trivial default constructor)
12097 if (!MemberInit.get() || MemberInit.isInvalid())
12098 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012099
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012100 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012101 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12102 SourceLocation(),
12103 MemberInit.takeAs<Expr>(),
12104 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012105 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012106
12107 // Be sure that the destructor is accessible and is marked as referenced.
12108 if (const RecordType *RecordTy
12109 = Context.getBaseElementType(Field->getType())
12110 ->getAs<RecordType>()) {
12111 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012112 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012113 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012114 CheckDestructorAccess(Field->getLocation(), Destructor,
12115 PDiag(diag::err_access_dtor_ivar)
12116 << Context.getBaseElementType(Field->getType()));
12117 }
12118 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012119 }
12120 ObjCImplementation->setIvarInitializers(Context,
12121 AllToInit.data(), AllToInit.size());
12122 }
12123}
Sean Huntfe57eef2011-05-04 05:57:24 +000012124
Sean Huntebcbe1d2011-05-04 23:29:54 +000012125static
12126void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12127 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12128 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12129 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12130 Sema &S) {
12131 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12132 CE = Current.end();
12133 if (Ctor->isInvalidDecl())
12134 return;
12135
Richard Smitha8eaf002012-08-23 06:16:52 +000012136 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12137
12138 // Target may not be determinable yet, for instance if this is a dependent
12139 // call in an uninstantiated template.
12140 if (Target) {
12141 const FunctionDecl *FNTarget = 0;
12142 (void)Target->hasBody(FNTarget);
12143 Target = const_cast<CXXConstructorDecl*>(
12144 cast_or_null<CXXConstructorDecl>(FNTarget));
12145 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012146
12147 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12148 // Avoid dereferencing a null pointer here.
12149 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12150
12151 if (!Current.insert(Canonical))
12152 return;
12153
12154 // We know that beyond here, we aren't chaining into a cycle.
12155 if (!Target || !Target->isDelegatingConstructor() ||
12156 Target->isInvalidDecl() || Valid.count(TCanonical)) {
12157 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12158 Valid.insert(*CI);
12159 Current.clear();
12160 // We've hit a cycle.
12161 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12162 Current.count(TCanonical)) {
12163 // If we haven't diagnosed this cycle yet, do so now.
12164 if (!Invalid.count(TCanonical)) {
12165 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012166 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012167 << Ctor;
12168
Richard Smitha8eaf002012-08-23 06:16:52 +000012169 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012170 if (TCanonical != Canonical)
12171 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12172
12173 CXXConstructorDecl *C = Target;
12174 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012175 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012176 (void)C->getTargetConstructor()->hasBody(FNTarget);
12177 assert(FNTarget && "Ctor cycle through bodiless function");
12178
Richard Smitha8eaf002012-08-23 06:16:52 +000012179 C = const_cast<CXXConstructorDecl*>(
12180 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012181 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12182 }
12183 }
12184
12185 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12186 Invalid.insert(*CI);
12187 Current.clear();
12188 } else {
12189 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12190 }
12191}
12192
12193
Sean Huntfe57eef2011-05-04 05:57:24 +000012194void Sema::CheckDelegatingCtorCycles() {
12195 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12196
Sean Huntebcbe1d2011-05-04 23:29:54 +000012197 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12198 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012199
Douglas Gregor0129b562011-07-27 21:57:17 +000012200 for (DelegatingCtorDeclsType::iterator
12201 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012202 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012203 I != E; ++I)
12204 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012205
12206 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12207 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012208}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012209
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012210namespace {
12211 /// \brief AST visitor that finds references to the 'this' expression.
12212 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12213 Sema &S;
12214
12215 public:
12216 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12217
12218 bool VisitCXXThisExpr(CXXThisExpr *E) {
12219 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12220 << E->isImplicit();
12221 return false;
12222 }
12223 };
12224}
12225
12226bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12227 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12228 if (!TSInfo)
12229 return false;
12230
12231 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012232 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012233 if (!ProtoTL)
12234 return false;
12235
12236 // C++11 [expr.prim.general]p3:
12237 // [The expression this] shall not appear before the optional
12238 // cv-qualifier-seq and it shall not appear within the declaration of a
12239 // static member function (although its type and value category are defined
12240 // within a static member function as they are within a non-static member
12241 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012242 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012243 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012244 FindCXXThisExpr Finder(*this);
12245
12246 // If the return type came after the cv-qualifier-seq, check it now.
12247 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012248 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012249 return true;
12250
12251 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012252 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12253 return true;
12254
12255 return checkThisInStaticMemberFunctionAttributes(Method);
12256}
12257
12258bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12259 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12260 if (!TSInfo)
12261 return false;
12262
12263 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012264 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012265 if (!ProtoTL)
12266 return false;
12267
David Blaikie39e6ab42013-02-18 22:06:02 +000012268 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012269 FindCXXThisExpr Finder(*this);
12270
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012271 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012272 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012273 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012274 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012275 case EST_DynamicNone:
12276 case EST_MSAny:
12277 case EST_None:
12278 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012279
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012280 case EST_ComputedNoexcept:
12281 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12282 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012283
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012284 case EST_Dynamic:
12285 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012286 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012287 E != EEnd; ++E) {
12288 if (!Finder.TraverseType(*E))
12289 return true;
12290 }
12291 break;
12292 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012293
12294 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012295}
12296
12297bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12298 FindCXXThisExpr Finder(*this);
12299
12300 // Check attributes.
12301 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12302 A != AEnd; ++A) {
12303 // FIXME: This should be emitted by tblgen.
12304 Expr *Arg = 0;
12305 ArrayRef<Expr *> Args;
12306 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12307 Arg = G->getArg();
12308 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12309 Arg = G->getArg();
12310 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12311 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12312 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12313 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12314 else if (ExclusiveLockFunctionAttr *ELF
12315 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12316 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12317 else if (SharedLockFunctionAttr *SLF
12318 = dyn_cast<SharedLockFunctionAttr>(*A))
12319 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12320 else if (ExclusiveTrylockFunctionAttr *ETLF
12321 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12322 Arg = ETLF->getSuccessValue();
12323 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12324 } else if (SharedTrylockFunctionAttr *STLF
12325 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12326 Arg = STLF->getSuccessValue();
12327 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12328 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12329 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12330 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12331 Arg = LR->getArg();
12332 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12333 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12334 else if (ExclusiveLocksRequiredAttr *ELR
12335 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12336 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12337 else if (SharedLocksRequiredAttr *SLR
12338 = dyn_cast<SharedLocksRequiredAttr>(*A))
12339 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12340
12341 if (Arg && !Finder.TraverseStmt(Arg))
12342 return true;
12343
12344 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12345 if (!Finder.TraverseStmt(Args[I]))
12346 return true;
12347 }
12348 }
12349
12350 return false;
12351}
12352
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012353void
12354Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12355 ArrayRef<ParsedType> DynamicExceptions,
12356 ArrayRef<SourceRange> DynamicExceptionRanges,
12357 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012358 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012359 FunctionProtoType::ExtProtoInfo &EPI) {
12360 Exceptions.clear();
12361 EPI.ExceptionSpecType = EST;
12362 if (EST == EST_Dynamic) {
12363 Exceptions.reserve(DynamicExceptions.size());
12364 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12365 // FIXME: Preserve type source info.
12366 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12367
12368 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12369 collectUnexpandedParameterPacks(ET, Unexpanded);
12370 if (!Unexpanded.empty()) {
12371 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12372 UPPC_ExceptionType,
12373 Unexpanded);
12374 continue;
12375 }
12376
12377 // Check that the type is valid for an exception spec, and
12378 // drop it if not.
12379 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12380 Exceptions.push_back(ET);
12381 }
12382 EPI.NumExceptions = Exceptions.size();
12383 EPI.Exceptions = Exceptions.data();
12384 return;
12385 }
12386
12387 if (EST == EST_ComputedNoexcept) {
12388 // If an error occurred, there's no expression here.
12389 if (NoexceptExpr) {
12390 assert((NoexceptExpr->isTypeDependent() ||
12391 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12392 Context.BoolTy) &&
12393 "Parser should have made sure that the expression is boolean");
12394 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12395 EPI.ExceptionSpecType = EST_BasicNoexcept;
12396 return;
12397 }
12398
12399 if (!NoexceptExpr->isValueDependent())
12400 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012401 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012402 /*AllowFold*/ false).take();
12403 EPI.NoexceptExpr = NoexceptExpr;
12404 }
12405 return;
12406 }
12407}
12408
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012409/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12410Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12411 // Implicitly declared functions (e.g. copy constructors) are
12412 // __host__ __device__
12413 if (D->isImplicit())
12414 return CFT_HostDevice;
12415
12416 if (D->hasAttr<CUDAGlobalAttr>())
12417 return CFT_Global;
12418
12419 if (D->hasAttr<CUDADeviceAttr>()) {
12420 if (D->hasAttr<CUDAHostAttr>())
12421 return CFT_HostDevice;
12422 else
12423 return CFT_Device;
12424 }
12425
12426 return CFT_Host;
12427}
12428
12429bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12430 CUDAFunctionTarget CalleeTarget) {
12431 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12432 // Callable from the device only."
12433 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12434 return true;
12435
12436 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12437 // Callable from the host only."
12438 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12439 // Callable from the host only."
12440 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12441 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12442 return true;
12443
12444 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12445 return true;
12446
12447 return false;
12448}
John McCall76da55d2013-04-16 07:28:30 +000012449
12450/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12451///
12452MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12453 SourceLocation DeclStart,
12454 Declarator &D, Expr *BitWidth,
12455 InClassInitStyle InitStyle,
12456 AccessSpecifier AS,
12457 AttributeList *MSPropertyAttr) {
12458 IdentifierInfo *II = D.getIdentifier();
12459 if (!II) {
12460 Diag(DeclStart, diag::err_anonymous_property);
12461 return NULL;
12462 }
12463 SourceLocation Loc = D.getIdentifierLoc();
12464
12465 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12466 QualType T = TInfo->getType();
12467 if (getLangOpts().CPlusPlus) {
12468 CheckExtraCXXDefaultArguments(D);
12469
12470 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12471 UPPC_DataMemberType)) {
12472 D.setInvalidType();
12473 T = Context.IntTy;
12474 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12475 }
12476 }
12477
12478 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12479
12480 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12481 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12482 diag::err_invalid_thread)
12483 << DeclSpec::getSpecifierName(TSCS);
12484
12485 // Check to see if this name was declared as a member previously
12486 NamedDecl *PrevDecl = 0;
12487 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12488 LookupName(Previous, S);
12489 switch (Previous.getResultKind()) {
12490 case LookupResult::Found:
12491 case LookupResult::FoundUnresolvedValue:
12492 PrevDecl = Previous.getAsSingle<NamedDecl>();
12493 break;
12494
12495 case LookupResult::FoundOverloaded:
12496 PrevDecl = Previous.getRepresentativeDecl();
12497 break;
12498
12499 case LookupResult::NotFound:
12500 case LookupResult::NotFoundInCurrentInstantiation:
12501 case LookupResult::Ambiguous:
12502 break;
12503 }
12504
12505 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12506 // Maybe we will complain about the shadowed template parameter.
12507 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12508 // Just pretend that we didn't see the previous declaration.
12509 PrevDecl = 0;
12510 }
12511
12512 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12513 PrevDecl = 0;
12514
12515 SourceLocation TSSL = D.getLocStart();
12516 MSPropertyDecl *NewPD;
12517 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12518 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12519 II, T, TInfo, TSSL,
12520 Data.GetterId, Data.SetterId);
12521 ProcessDeclAttributes(TUScope, NewPD, D);
12522 NewPD->setAccess(AS);
12523
12524 if (NewPD->isInvalidDecl())
12525 Record->setInvalidDecl();
12526
12527 if (D.getDeclSpec().isModulePrivateSpecified())
12528 NewPD->setModulePrivate();
12529
12530 if (NewPD->isInvalidDecl() && PrevDecl) {
12531 // Don't introduce NewFD into scope; there's already something
12532 // with the same name in the same scope.
12533 } else if (II) {
12534 PushOnScopeChains(NewPD, S);
12535 } else
12536 Record->addDecl(NewPD);
12537
12538 return NewPD;
12539}