blob: 0bea565f937b26acb93ad59692a6d311d5c01918 [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);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
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
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
Douglas Gregorc6889e72012-02-14 22:28:59 +0000636 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
637 isa<CXXMethodDecl>(FD) &&
638 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
639
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 // Find first parameter with a default argument
641 for (p = 0; p < NumParams; ++p) {
642 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000643 if (Param->hasDefaultArg()) {
644 // C++11 [expr.prim.lambda]p5:
645 // [...] Default arguments (8.3.6) shall not be specified in the
646 // parameter-declaration-clause of a lambda-declarator.
647 //
648 // FIXME: Core issue 974 strikes this sentence, we only provide an
649 // extension warning.
650 if (IsLambda)
651 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
652 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000653 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000654 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000655 }
656
657 // C++ [dcl.fct.default]p4:
658 // In a given function declaration, all parameters
659 // subsequent to a parameter with a default argument shall
660 // have default arguments supplied in this or previous
661 // declarations. A default argument shall not be redefined
662 // by a later declaration (not even to the same value).
663 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000664 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000665 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000666 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000667 if (Param->isInvalidDecl())
668 /* We already complained about this parameter. */;
669 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000670 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000671 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000672 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000673 else
Mike Stump1eb44332009-09-09 15:08:12 +0000674 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattner3d1cee32008-04-08 05:04:30 +0000677 LastMissingDefaultArg = p;
678 }
679 }
680
681 if (LastMissingDefaultArg > 0) {
682 // Some default arguments were missing. Clear out all of the
683 // default arguments up to (and including) the last missing
684 // default argument, so that we leave the function parameters
685 // in a semantically valid state.
686 for (p = 0; p <= LastMissingDefaultArg; ++p) {
687 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000688 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000689 Param->setDefaultArg(0);
690 }
691 }
692 }
693}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000694
Richard Smith9f569cc2011-10-01 02:31:28 +0000695// CheckConstexprParameterTypes - Check whether a function's parameter types
696// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000697// diagnostic and return false.
698static bool CheckConstexprParameterTypes(Sema &SemaRef,
699 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000700 unsigned ArgIndex = 0;
701 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
702 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
703 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
704 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
705 SourceLocation ParamLoc = PD->getLocation();
706 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000707 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000708 diag::err_constexpr_non_literal_param,
709 ArgIndex+1, PD->getSourceRange(),
710 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000711 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 }
Joao Matos17d35c32012-08-31 22:18:20 +0000713 return true;
714}
715
716/// \brief Get diagnostic %select index for tag kind for
717/// record diagnostic message.
718/// WARNING: Indexes apply to particular diagnostics only!
719///
720/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000721static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000722 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000723 case TTK_Struct: return 0;
724 case TTK_Interface: return 1;
725 case TTK_Class: return 2;
726 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000727 }
Joao Matos17d35c32012-08-31 22:18:20 +0000728}
729
730// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
731// the requirements of a constexpr function definition or a constexpr
732// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000733// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000734//
Richard Smith86c3ae42012-02-13 03:54:03 +0000735// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
736bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
738 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000739 // C++11 [dcl.constexpr]p4:
740 // The definition of a constexpr constructor shall satisfy the following
741 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000743 const CXXRecordDecl *RD = MD->getParent();
744 if (RD->getNumVBases()) {
745 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
746 << isa<CXXConstructorDecl>(NewFD)
747 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
748 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
749 E = RD->vbases_end(); I != E; ++I)
750 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 return false;
753 }
Richard Smith35340502012-01-13 04:54:00 +0000754 }
755
756 if (!isa<CXXConstructorDecl>(NewFD)) {
757 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000758 // The definition of a constexpr function shall satisfy the following
759 // constraints:
760 // - it shall not be virtual;
761 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
762 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000763 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000764
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 // If it's not obvious why this function is virtual, find an overridden
766 // function which uses the 'virtual' keyword.
767 const CXXMethodDecl *WrittenVirtual = Method;
768 while (!WrittenVirtual->isVirtualAsWritten())
769 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
770 if (WrittenVirtual != Method)
771 Diag(WrittenVirtual->getLocation(),
772 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000773 return false;
774 }
775
776 // - its return type shall be a literal type;
777 QualType RT = NewFD->getResultType();
778 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000779 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000780 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000781 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000782 }
783
Richard Smith35340502012-01-13 04:54:00 +0000784 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000785 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000786 return false;
787
Richard Smith9f569cc2011-10-01 02:31:28 +0000788 return true;
789}
790
791/// Check the given declaration statement is legal within a constexpr function
792/// body. C++0x [dcl.constexpr]p3,p4.
793///
794/// \return true if the body is OK, false if we have diagnosed a problem.
795static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
796 DeclStmt *DS) {
797 // C++0x [dcl.constexpr]p3 and p4:
798 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
799 // contain only
800 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
801 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
802 switch ((*DclIt)->getKind()) {
803 case Decl::StaticAssert:
804 case Decl::Using:
805 case Decl::UsingShadow:
806 case Decl::UsingDirective:
807 case Decl::UnresolvedUsingTypename:
808 // - static_assert-declarations
809 // - using-declarations,
810 // - using-directives,
811 continue;
812
813 case Decl::Typedef:
814 case Decl::TypeAlias: {
815 // - typedef declarations and alias-declarations that do not define
816 // classes or enumerations,
817 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
818 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
819 // Don't allow variably-modified types in constexpr functions.
820 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
821 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
822 << TL.getSourceRange() << TL.getType()
823 << isa<CXXConstructorDecl>(Dcl);
824 return false;
825 }
826 continue;
827 }
828
829 case Decl::Enum:
830 case Decl::CXXRecord:
831 // As an extension, we allow the declaration (but not the definition) of
832 // classes and enumerations in all declarations, not just in typedef and
833 // alias declarations.
834 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
835 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
836 << isa<CXXConstructorDecl>(Dcl);
837 return false;
838 }
839 continue;
840
841 case Decl::Var:
842 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
843 << isa<CXXConstructorDecl>(Dcl);
844 return false;
845
846 default:
847 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
848 << isa<CXXConstructorDecl>(Dcl);
849 return false;
850 }
851 }
852
853 return true;
854}
855
856/// Check that the given field is initialized within a constexpr constructor.
857///
858/// \param Dcl The constexpr constructor being checked.
859/// \param Field The field being checked. This may be a member of an anonymous
860/// struct or union nested within the class being checked.
861/// \param Inits All declarations, including anonymous struct/union members and
862/// indirect members, for which any initialization was provided.
863/// \param Diagnosed Set to true if an error is produced.
864static void CheckConstexprCtorInitializer(Sema &SemaRef,
865 const FunctionDecl *Dcl,
866 FieldDecl *Field,
867 llvm::SmallSet<Decl*, 16> &Inits,
868 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000869 if (Field->isUnnamedBitfield())
870 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000871
872 if (Field->isAnonymousStructOrUnion() &&
873 Field->getType()->getAsCXXRecordDecl()->isEmpty())
874 return;
875
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 if (!Inits.count(Field)) {
877 if (!Diagnosed) {
878 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
879 Diagnosed = true;
880 }
881 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
882 } else if (Field->isAnonymousStructOrUnion()) {
883 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
884 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
885 I != E; ++I)
886 // If an anonymous union contains an anonymous struct of which any member
887 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000888 if (!RD->isUnion() || Inits.count(*I))
889 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000890 }
891}
892
893/// Check the body for the given constexpr function declaration only contains
894/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
895///
896/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000897bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000898 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000899 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000900 // The definition of a constexpr function shall satisfy the following
901 // constraints: [...]
902 // - its function-body shall be = delete, = default, or a
903 // compound-statement
904 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000905 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000906 // In the definition of a constexpr constructor, [...]
907 // - its function-body shall not be a function-try-block;
908 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
909 << isa<CXXConstructorDecl>(Dcl);
910 return false;
911 }
912
913 // - its function-body shall be [...] a compound-statement that contains only
914 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
915
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000916 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000917 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
918 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
919 switch ((*BodyIt)->getStmtClass()) {
920 case Stmt::NullStmtClass:
921 // - null statements,
922 continue;
923
924 case Stmt::DeclStmtClass:
925 // - static_assert-declarations
926 // - using-declarations,
927 // - using-directives,
928 // - typedef declarations and alias-declarations that do not define
929 // classes or enumerations,
930 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
931 return false;
932 continue;
933
934 case Stmt::ReturnStmtClass:
935 // - and exactly one return statement;
936 if (isa<CXXConstructorDecl>(Dcl))
937 break;
938
939 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000940 continue;
941
942 default:
943 break;
944 }
945
946 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
947 << isa<CXXConstructorDecl>(Dcl);
948 return false;
949 }
950
951 if (const CXXConstructorDecl *Constructor
952 = dyn_cast<CXXConstructorDecl>(Dcl)) {
953 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000954 // DR1359:
955 // - every non-variant non-static data member and base class sub-object
956 // shall be initialized;
957 // - if the class is a non-empty union, or for each non-empty anonymous
958 // union member of a non-union class, exactly one non-static data member
959 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000960 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000961 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000962 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
963 return false;
964 }
Richard Smith6e433752011-10-10 16:38:04 +0000965 } else if (!Constructor->isDependentContext() &&
966 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000967 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
968
969 // Skip detailed checking if we have enough initializers, and we would
970 // allow at most one initializer per member.
971 bool AnyAnonStructUnionMembers = false;
972 unsigned Fields = 0;
973 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
974 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000975 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000976 AnyAnonStructUnionMembers = true;
977 break;
978 }
979 }
980 if (AnyAnonStructUnionMembers ||
981 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
982 // Check initialization of non-static data members. Base classes are
983 // always initialized so do not need to be checked. Dependent bases
984 // might not have initializers in the member initializer list.
985 llvm::SmallSet<Decl*, 16> Inits;
986 for (CXXConstructorDecl::init_const_iterator
987 I = Constructor->init_begin(), E = Constructor->init_end();
988 I != E; ++I) {
989 if (FieldDecl *FD = (*I)->getMember())
990 Inits.insert(FD);
991 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
992 Inits.insert(ID->chain_begin(), ID->chain_end());
993 }
994
995 bool Diagnosed = false;
996 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
997 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000998 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000999 if (Diagnosed)
1000 return false;
1001 }
1002 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001003 } else {
1004 if (ReturnStmts.empty()) {
1005 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
1006 return false;
1007 }
1008 if (ReturnStmts.size() > 1) {
1009 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
1010 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1011 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1012 return false;
1013 }
1014 }
1015
Richard Smith5ba73e12012-02-04 00:33:54 +00001016 // C++11 [dcl.constexpr]p5:
1017 // if no function argument values exist such that the function invocation
1018 // substitution would produce a constant expression, the program is
1019 // ill-formed; no diagnostic required.
1020 // C++11 [dcl.constexpr]p3:
1021 // - every constructor call and implicit conversion used in initializing the
1022 // return value shall be one of those allowed in a constant expression.
1023 // C++11 [dcl.constexpr]p4:
1024 // - every constructor involved in initializing non-static data members and
1025 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001026 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001027 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001028 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001029 << isa<CXXConstructorDecl>(Dcl);
1030 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1031 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001032 // Don't return false here: we allow this for compatibility in
1033 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001034 }
1035
Richard Smith9f569cc2011-10-01 02:31:28 +00001036 return true;
1037}
1038
Douglas Gregorb48fe382008-10-31 09:07:45 +00001039/// isCurrentClassName - Determine whether the identifier II is the
1040/// name of the class type currently being defined. In the case of
1041/// nested classes, this will only return true if II is the name of
1042/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001043bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1044 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001045 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001046
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001047 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001048 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001049 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001050 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1051 } else
1052 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1053
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001054 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001055 return &II == CurDecl->getIdentifier();
1056 else
1057 return false;
1058}
1059
Douglas Gregor229d47a2012-11-10 07:24:09 +00001060/// \brief Determine whether the given class is a base class of the given
1061/// class, including looking at dependent bases.
1062static bool findCircularInheritance(const CXXRecordDecl *Class,
1063 const CXXRecordDecl *Current) {
1064 SmallVector<const CXXRecordDecl*, 8> Queue;
1065
1066 Class = Class->getCanonicalDecl();
1067 while (true) {
1068 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1069 E = Current->bases_end();
1070 I != E; ++I) {
1071 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1072 if (!Base)
1073 continue;
1074
1075 Base = Base->getDefinition();
1076 if (!Base)
1077 continue;
1078
1079 if (Base->getCanonicalDecl() == Class)
1080 return true;
1081
1082 Queue.push_back(Base);
1083 }
1084
1085 if (Queue.empty())
1086 return false;
1087
1088 Current = Queue.back();
1089 Queue.pop_back();
1090 }
1091
1092 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001093}
1094
Mike Stump1eb44332009-09-09 15:08:12 +00001095/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001096///
1097/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1098/// and returns NULL otherwise.
1099CXXBaseSpecifier *
1100Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1101 SourceRange SpecifierRange,
1102 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001103 TypeSourceInfo *TInfo,
1104 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001105 QualType BaseType = TInfo->getType();
1106
Douglas Gregor2943aed2009-03-03 04:44:36 +00001107 // C++ [class.union]p1:
1108 // A union shall not have base classes.
1109 if (Class->isUnion()) {
1110 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1111 << SpecifierRange;
1112 return 0;
1113 }
1114
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 if (EllipsisLoc.isValid() &&
1116 !TInfo->getType()->containsUnexpandedParameterPack()) {
1117 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1118 << TInfo->getTypeLoc().getSourceRange();
1119 EllipsisLoc = SourceLocation();
1120 }
Douglas Gregord777e282012-11-10 01:18:17 +00001121
1122 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1123
1124 if (BaseType->isDependentType()) {
1125 // Make sure that we don't have circular inheritance among our dependent
1126 // bases. For non-dependent bases, the check for completeness below handles
1127 // this.
1128 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1129 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1130 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001131 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001132 Diag(BaseLoc, diag::err_circular_inheritance)
1133 << BaseType << Context.getTypeDeclType(Class);
1134
1135 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1136 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1137 << BaseType;
1138
1139 return 0;
1140 }
1141 }
1142
Mike Stump1eb44332009-09-09 15:08:12 +00001143 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001144 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001145 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001146 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001147
1148 // Base specifiers must be record types.
1149 if (!BaseType->isRecordType()) {
1150 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1151 return 0;
1152 }
1153
1154 // C++ [class.union]p1:
1155 // A union shall not be used as a base class.
1156 if (BaseType->isUnionType()) {
1157 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1158 return 0;
1159 }
1160
1161 // C++ [class.derived]p2:
1162 // The class-name in a base-specifier shall not be an incompletely
1163 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001164 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001165 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001166 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001167 return 0;
John McCall572fc622010-08-17 07:23:57 +00001168 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001169
Eli Friedman1d954f62009-08-15 21:55:26 +00001170 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001171 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001172 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001173 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001174 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001175 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1176 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001177
Anders Carlsson1d209272011-03-25 14:55:14 +00001178 // C++ [class]p3:
1179 // If a class is marked final and it appears as a base-type-specifier in
1180 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001181 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001182 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1183 << CXXBaseDecl->getDeclName();
1184 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1185 << CXXBaseDecl->getDeclName();
1186 return 0;
1187 }
1188
John McCall572fc622010-08-17 07:23:57 +00001189 if (BaseDecl->isInvalidDecl())
1190 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001191
1192 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001193 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001194 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001195 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001196}
1197
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001198/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1199/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001200/// example:
1201/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001202/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001203BaseResult
John McCalld226f652010-08-21 09:40:31 +00001204Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001205 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001206 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001207 ParsedType basetype, SourceLocation BaseLoc,
1208 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001209 if (!classdecl)
1210 return true;
1211
Douglas Gregor40808ce2009-03-09 23:48:35 +00001212 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001213 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001214 if (!Class)
1215 return true;
1216
Richard Smith05321402013-02-19 23:47:15 +00001217 // We do not support any C++11 attributes on base-specifiers yet.
1218 // Diagnose any attributes we see.
1219 if (!Attributes.empty()) {
1220 for (AttributeList *Attr = Attributes.getList(); Attr;
1221 Attr = Attr->getNext()) {
1222 if (Attr->isInvalid() ||
1223 Attr->getKind() == AttributeList::IgnoredAttribute)
1224 continue;
1225 Diag(Attr->getLoc(),
1226 Attr->getKind() == AttributeList::UnknownAttribute
1227 ? diag::warn_unknown_attribute_ignored
1228 : diag::err_base_specifier_attribute)
1229 << Attr->getName();
1230 }
1231 }
1232
Nick Lewycky56062202010-07-26 16:56:01 +00001233 TypeSourceInfo *TInfo = 0;
1234 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001235
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001236 if (EllipsisLoc.isInvalid() &&
1237 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001238 UPPC_BaseType))
1239 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001240
Douglas Gregor2943aed2009-03-03 04:44:36 +00001241 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 Virtual, Access, TInfo,
1243 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001244 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001245 else
1246 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Douglas Gregor2943aed2009-03-03 04:44:36 +00001248 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001249}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001250
Douglas Gregor2943aed2009-03-03 04:44:36 +00001251/// \brief Performs the actual work of attaching the given base class
1252/// specifiers to a C++ class.
1253bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1254 unsigned NumBases) {
1255 if (NumBases == 0)
1256 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001257
1258 // Used to keep track of which base types we have already seen, so
1259 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001260 // that the key is always the unqualified canonical type of the base
1261 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001262 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1263
1264 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001265 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001266 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001267 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001268 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001269 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001270 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001271
1272 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1273 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001274 // C++ [class.mi]p3:
1275 // A class shall not be specified as a direct base class of a
1276 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001277 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001278 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001279 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001280 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001281
1282 // Delete the duplicate base class specifier; we're going to
1283 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001284 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001285
1286 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001287 } else {
1288 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001289 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001290 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001291 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1292 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1293 if (Class->isInterface() &&
1294 (!RD->isInterface() ||
1295 KnownBase->getAccessSpecifier() != AS_public)) {
1296 // The Microsoft extension __interface does not permit bases that
1297 // are not themselves public interfaces.
1298 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1299 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1300 << RD->getSourceRange();
1301 Invalid = true;
1302 }
1303 if (RD->hasAttr<WeakAttr>())
1304 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1305 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001306 }
1307 }
1308
1309 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001310 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001311
1312 // Delete the remaining (good) base class specifiers, since their
1313 // data has been copied into the CXXRecordDecl.
1314 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001315 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001316
1317 return Invalid;
1318}
1319
1320/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1321/// class, after checking whether there are any duplicate base
1322/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001323void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001324 unsigned NumBases) {
1325 if (!ClassDecl || !Bases || !NumBases)
1326 return;
1327
1328 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001329 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001330 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001331}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001332
Douglas Gregora8f32e02009-10-06 17:59:45 +00001333/// \brief Determine whether the type \p Derived is a C++ class that is
1334/// derived from the type \p Base.
1335bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001336 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001337 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001338
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001339 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001340 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001341 return false;
1342
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001343 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001344 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001346
1347 // If either the base or the derived type is invalid, don't try to
1348 // check whether one is derived from the other.
1349 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1350 return false;
1351
John McCall86ff3082010-02-04 22:26:26 +00001352 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1353 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001354}
1355
1356/// \brief Determine whether the type \p Derived is a C++ class that is
1357/// derived from the type \p Base.
1358bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001359 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001360 return false;
1361
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001362 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001363 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001364 return false;
1365
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001366 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001367 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001368 return false;
1369
Douglas Gregora8f32e02009-10-06 17:59:45 +00001370 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1371}
1372
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001373void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001374 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001375 assert(BasePathArray.empty() && "Base path array must be empty!");
1376 assert(Paths.isRecordingPaths() && "Must record paths!");
1377
1378 const CXXBasePath &Path = Paths.front();
1379
1380 // We first go backward and check if we have a virtual base.
1381 // FIXME: It would be better if CXXBasePath had the base specifier for
1382 // the nearest virtual base.
1383 unsigned Start = 0;
1384 for (unsigned I = Path.size(); I != 0; --I) {
1385 if (Path[I - 1].Base->isVirtual()) {
1386 Start = I - 1;
1387 break;
1388 }
1389 }
1390
1391 // Now add all bases.
1392 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001393 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001394}
1395
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001396/// \brief Determine whether the given base path includes a virtual
1397/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001398bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1399 for (CXXCastPath::const_iterator B = BasePath.begin(),
1400 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001401 B != BEnd; ++B)
1402 if ((*B)->isVirtual())
1403 return true;
1404
1405 return false;
1406}
1407
Douglas Gregora8f32e02009-10-06 17:59:45 +00001408/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1409/// conversion (where Derived and Base are class types) is
1410/// well-formed, meaning that the conversion is unambiguous (and
1411/// that all of the base classes are accessible). Returns true
1412/// and emits a diagnostic if the code is ill-formed, returns false
1413/// otherwise. Loc is the location where this routine should point to
1414/// if there is an error, and Range is the source range to highlight
1415/// if there is an error.
1416bool
1417Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001418 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001419 unsigned AmbigiousBaseConvID,
1420 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001421 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001422 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001423 // First, determine whether the path from Derived to Base is
1424 // ambiguous. This is slightly more expensive than checking whether
1425 // the Derived to Base conversion exists, because here we need to
1426 // explore multiple paths to determine if there is an ambiguity.
1427 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1428 /*DetectVirtual=*/false);
1429 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1430 assert(DerivationOkay &&
1431 "Can only be used with a derived-to-base conversion");
1432 (void)DerivationOkay;
1433
1434 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001435 if (InaccessibleBaseID) {
1436 // Check that the base class can be accessed.
1437 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1438 InaccessibleBaseID)) {
1439 case AR_inaccessible:
1440 return true;
1441 case AR_accessible:
1442 case AR_dependent:
1443 case AR_delayed:
1444 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001445 }
John McCall6b2accb2010-02-10 09:31:12 +00001446 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001447
1448 // Build a base path if necessary.
1449 if (BasePath)
1450 BuildBasePathArray(Paths, *BasePath);
1451 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001452 }
1453
1454 // We know that the derived-to-base conversion is ambiguous, and
1455 // we're going to produce a diagnostic. Perform the derived-to-base
1456 // search just one more time to compute all of the possible paths so
1457 // that we can print them out. This is more expensive than any of
1458 // the previous derived-to-base checks we've done, but at this point
1459 // performance isn't as much of an issue.
1460 Paths.clear();
1461 Paths.setRecordingPaths(true);
1462 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1463 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1464 (void)StillOkay;
1465
1466 // Build up a textual representation of the ambiguous paths, e.g.,
1467 // D -> B -> A, that will be used to illustrate the ambiguous
1468 // conversions in the diagnostic. We only print one of the paths
1469 // to each base class subobject.
1470 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1471
1472 Diag(Loc, AmbigiousBaseConvID)
1473 << Derived << Base << PathDisplayStr << Range << Name;
1474 return true;
1475}
1476
1477bool
1478Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001479 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001480 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001481 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001482 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001483 IgnoreAccess ? 0
1484 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001485 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001486 Loc, Range, DeclarationName(),
1487 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001488}
1489
1490
1491/// @brief Builds a string representing ambiguous paths from a
1492/// specific derived class to different subobjects of the same base
1493/// class.
1494///
1495/// This function builds a string that can be used in error messages
1496/// to show the different paths that one can take through the
1497/// inheritance hierarchy to go from the derived class to different
1498/// subobjects of a base class. The result looks something like this:
1499/// @code
1500/// struct D -> struct B -> struct A
1501/// struct D -> struct C -> struct A
1502/// @endcode
1503std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1504 std::string PathDisplayStr;
1505 std::set<unsigned> DisplayedPaths;
1506 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1507 Path != Paths.end(); ++Path) {
1508 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1509 // We haven't displayed a path to this particular base
1510 // class subobject yet.
1511 PathDisplayStr += "\n ";
1512 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1513 for (CXXBasePath::const_iterator Element = Path->begin();
1514 Element != Path->end(); ++Element)
1515 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1516 }
1517 }
1518
1519 return PathDisplayStr;
1520}
1521
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001522//===----------------------------------------------------------------------===//
1523// C++ class member Handling
1524//===----------------------------------------------------------------------===//
1525
Abramo Bagnara6206d532010-06-05 05:09:32 +00001526/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001527bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1528 SourceLocation ASLoc,
1529 SourceLocation ColonLoc,
1530 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001531 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001532 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001533 ASLoc, ColonLoc);
1534 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001535 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001536}
1537
Richard Smitha4b39652012-08-06 03:25:17 +00001538/// CheckOverrideControl - Check C++11 override control semantics.
1539void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001540 if (D->isInvalidDecl())
1541 return;
1542
Chris Lattner5f9e2722011-07-23 10:55:15 +00001543 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001544
Richard Smitha4b39652012-08-06 03:25:17 +00001545 // Do we know which functions this declaration might be overriding?
1546 bool OverridesAreKnown = !MD ||
1547 (!MD->getParent()->hasAnyDependentBases() &&
1548 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001549
Richard Smitha4b39652012-08-06 03:25:17 +00001550 if (!MD || !MD->isVirtual()) {
1551 if (OverridesAreKnown) {
1552 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1553 Diag(OA->getLocation(),
1554 diag::override_keyword_only_allowed_on_virtual_member_functions)
1555 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1556 D->dropAttr<OverrideAttr>();
1557 }
1558 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1559 Diag(FA->getLocation(),
1560 diag::override_keyword_only_allowed_on_virtual_member_functions)
1561 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1562 D->dropAttr<FinalAttr>();
1563 }
1564 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001565 return;
1566 }
Richard Smitha4b39652012-08-06 03:25:17 +00001567
1568 if (!OverridesAreKnown)
1569 return;
1570
1571 // C++11 [class.virtual]p5:
1572 // If a virtual function is marked with the virt-specifier override and
1573 // does not override a member function of a base class, the program is
1574 // ill-formed.
1575 bool HasOverriddenMethods =
1576 MD->begin_overridden_methods() != MD->end_overridden_methods();
1577 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1578 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1579 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001580}
1581
Richard Smitha4b39652012-08-06 03:25:17 +00001582/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001583/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001584/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001585bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1586 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001587 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001588 return false;
1589
1590 Diag(New->getLocation(), diag::err_final_function_overridden)
1591 << New->getDeclName();
1592 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1593 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001594}
1595
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001596static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001597 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1598 // FIXME: Destruction of ObjC lifetime types has side-effects.
1599 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1600 return !RD->isCompleteDefinition() ||
1601 !RD->hasTrivialDefaultConstructor() ||
1602 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001603 return false;
1604}
1605
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001606/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1607/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001608/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001609/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1610/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001611NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001612Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001613 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001614 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001615 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001616 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001617 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1618 DeclarationName Name = NameInfo.getName();
1619 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001620
1621 // For anonymous bitfields, the location should point to the type.
1622 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001623 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001624
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001625 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001626
John McCall4bde1e12010-06-04 08:34:12 +00001627 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001628 assert(!DS.isFriendSpecified());
1629
Richard Smith1ab0d902011-06-25 02:28:38 +00001630 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001631
John McCalle402e722012-09-25 07:32:39 +00001632 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1633 // The Microsoft extension __interface only permits public member functions
1634 // and prohibits constructors, destructors, operators, non-public member
1635 // functions, static methods and data members.
1636 unsigned InvalidDecl;
1637 bool ShowDeclName = true;
1638 if (!isFunc)
1639 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1640 else if (AS != AS_public)
1641 InvalidDecl = 2;
1642 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1643 InvalidDecl = 3;
1644 else switch (Name.getNameKind()) {
1645 case DeclarationName::CXXConstructorName:
1646 InvalidDecl = 4;
1647 ShowDeclName = false;
1648 break;
1649
1650 case DeclarationName::CXXDestructorName:
1651 InvalidDecl = 5;
1652 ShowDeclName = false;
1653 break;
1654
1655 case DeclarationName::CXXOperatorName:
1656 case DeclarationName::CXXConversionFunctionName:
1657 InvalidDecl = 6;
1658 break;
1659
1660 default:
1661 InvalidDecl = 0;
1662 break;
1663 }
1664
1665 if (InvalidDecl) {
1666 if (ShowDeclName)
1667 Diag(Loc, diag::err_invalid_member_in_interface)
1668 << (InvalidDecl-1) << Name;
1669 else
1670 Diag(Loc, diag::err_invalid_member_in_interface)
1671 << (InvalidDecl-1) << "";
1672 return 0;
1673 }
1674 }
1675
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001676 // C++ 9.2p6: A member shall not be declared to have automatic storage
1677 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001678 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1679 // data members and cannot be applied to names declared const or static,
1680 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001681 switch (DS.getStorageClassSpec()) {
1682 case DeclSpec::SCS_unspecified:
1683 case DeclSpec::SCS_typedef:
1684 case DeclSpec::SCS_static:
1685 // FALL THROUGH.
1686 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001687 case DeclSpec::SCS_mutable:
1688 if (isFunc) {
1689 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001690 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001691 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001692 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Sebastian Redla11f42f2008-11-17 23:24:37 +00001694 // FIXME: It would be nicer if the keyword was ignored only for this
1695 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001696 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001697 }
1698 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001699 default:
1700 if (DS.getStorageClassSpecLoc().isValid())
1701 Diag(DS.getStorageClassSpecLoc(),
1702 diag::err_storageclass_invalid_for_member);
1703 else
1704 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1705 D.getMutableDeclSpec().ClearStorageClassSpecs();
1706 }
1707
Sebastian Redl669d5d72008-11-14 23:42:31 +00001708 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1709 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001710 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001711
David Blaikie1d87fba2013-01-30 01:22:18 +00001712 if (DS.isConstexprSpecified() && isInstField) {
1713 SemaDiagnosticBuilder B =
1714 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1715 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1716 if (InitStyle == ICIS_NoInit) {
1717 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1718 D.getMutableDeclSpec().ClearConstexprSpec();
1719 const char *PrevSpec;
1720 unsigned DiagID;
1721 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1722 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001723 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001724 assert(!Failed && "Making a constexpr member const shouldn't fail");
1725 } else {
1726 B << 1;
1727 const char *PrevSpec;
1728 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001729 if (D.getMutableDeclSpec().SetStorageClassSpec(
1730 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001731 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001732 "This is the only DeclSpec that should fail to be applied");
1733 B << 1;
1734 } else {
1735 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1736 isInstField = false;
1737 }
1738 }
1739 }
1740
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001741 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001742 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001743 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001744
1745 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001746 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001747 Diag(Loc, diag::err_bad_variable_name)
1748 << Name;
1749 return 0;
1750 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001751
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001752 IdentifierInfo *II = Name.getAsIdentifierInfo();
1753
Douglas Gregorf2503652011-09-21 14:40:46 +00001754 // Member field could not be with "template" keyword.
1755 // So TemplateParameterLists should be empty in this case.
1756 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001757 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001758 if (TemplateParams->size()) {
1759 // There is no such thing as a member field template.
1760 Diag(D.getIdentifierLoc(), diag::err_template_member)
1761 << II
1762 << SourceRange(TemplateParams->getTemplateLoc(),
1763 TemplateParams->getRAngleLoc());
1764 } else {
1765 // There is an extraneous 'template<>' for this member.
1766 Diag(TemplateParams->getTemplateLoc(),
1767 diag::err_template_member_noparams)
1768 << II
1769 << SourceRange(TemplateParams->getTemplateLoc(),
1770 TemplateParams->getRAngleLoc());
1771 }
1772 return 0;
1773 }
1774
Douglas Gregor922fff22010-10-13 22:19:53 +00001775 if (SS.isSet() && !SS.isInvalid()) {
1776 // The user provided a superfluous scope specifier inside a class
1777 // definition:
1778 //
1779 // class X {
1780 // int X::member;
1781 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001782 if (DeclContext *DC = computeDeclContext(SS, false))
1783 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001784 else
1785 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1786 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001787
Douglas Gregor922fff22010-10-13 22:19:53 +00001788 SS.clear();
1789 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001790
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001791 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001792 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001793 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001794 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001795 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001796
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001797 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001798 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001799 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001800 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001801
1802 // Non-instance-fields can't have a bitfield.
1803 if (BitWidth) {
1804 if (Member->isInvalidDecl()) {
1805 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001806 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001807 // C++ 9.6p3: A bit-field shall not be a static member.
1808 // "static member 'A' cannot be a bit-field"
1809 Diag(Loc, diag::err_static_not_bitfield)
1810 << Name << BitWidth->getSourceRange();
1811 } else if (isa<TypedefDecl>(Member)) {
1812 // "typedef member 'x' cannot be a bit-field"
1813 Diag(Loc, diag::err_typedef_not_bitfield)
1814 << Name << BitWidth->getSourceRange();
1815 } else {
1816 // A function typedef ("typedef int f(); f a;").
1817 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1818 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001819 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001820 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001821 }
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Chris Lattner8b963ef2009-03-05 23:01:03 +00001823 BitWidth = 0;
1824 Member->setInvalidDecl();
1825 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001826
1827 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Douglas Gregor37b372b2009-08-20 22:52:58 +00001829 // If we have declared a member function template, set the access of the
1830 // templated declaration as well.
1831 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1832 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001833 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001834
Richard Smitha4b39652012-08-06 03:25:17 +00001835 if (VS.isOverrideSpecified())
1836 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1837 if (VS.isFinalSpecified())
1838 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001839
Douglas Gregorf5251602011-03-08 17:10:18 +00001840 if (VS.getLastLocation().isValid()) {
1841 // Update the end location of a method that has a virt-specifiers.
1842 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1843 MD->setRangeEnd(VS.getLastLocation());
1844 }
Richard Smitha4b39652012-08-06 03:25:17 +00001845
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001846 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001847
Douglas Gregor10bd3682008-11-17 22:58:34 +00001848 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001849
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001850 if (isInstField) {
1851 FieldDecl *FD = cast<FieldDecl>(Member);
1852 FieldCollector->Add(FD);
1853
1854 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1855 FD->getLocation())
1856 != DiagnosticsEngine::Ignored) {
1857 // Remember all explicit private FieldDecls that have a name, no side
1858 // effects and are not part of a dependent type declaration.
1859 if (!FD->isImplicit() && FD->getDeclName() &&
1860 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001861 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001862 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001863 !InitializationHasSideEffects(*FD))
1864 UnusedPrivateFields.insert(FD);
1865 }
1866 }
1867
John McCalld226f652010-08-21 09:40:31 +00001868 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001869}
1870
Hans Wennborg471f9852012-09-18 15:58:06 +00001871namespace {
1872 class UninitializedFieldVisitor
1873 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1874 Sema &S;
1875 ValueDecl *VD;
1876 public:
1877 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1878 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001879 S(S) {
1880 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1881 this->VD = IFD->getAnonField();
1882 else
1883 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001884 }
1885
1886 void HandleExpr(Expr *E) {
1887 if (!E) return;
1888
1889 // Expressions like x(x) sometimes lack the surrounding expressions
1890 // but need to be checked anyways.
1891 HandleValue(E);
1892 Visit(E);
1893 }
1894
1895 void HandleValue(Expr *E) {
1896 E = E->IgnoreParens();
1897
1898 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1899 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001900 return;
1901
1902 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1903 // or union.
1904 MemberExpr *FieldME = ME;
1905
Hans Wennborg471f9852012-09-18 15:58:06 +00001906 Expr *Base = E;
1907 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001908 ME = cast<MemberExpr>(Base);
1909
1910 if (isa<VarDecl>(ME->getMemberDecl()))
1911 return;
1912
1913 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1914 if (!FD->isAnonymousStructOrUnion())
1915 FieldME = ME;
1916
Hans Wennborg471f9852012-09-18 15:58:06 +00001917 Base = ME->getBase();
1918 }
1919
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001920 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001921 unsigned diag = VD->getType()->isReferenceType()
1922 ? diag::warn_reference_field_is_uninit
1923 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001924 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001925 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001926 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001927 }
1928
1929 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1930 HandleValue(CO->getTrueExpr());
1931 HandleValue(CO->getFalseExpr());
1932 return;
1933 }
1934
1935 if (BinaryConditionalOperator *BCO =
1936 dyn_cast<BinaryConditionalOperator>(E)) {
1937 HandleValue(BCO->getCommon());
1938 HandleValue(BCO->getFalseExpr());
1939 return;
1940 }
1941
1942 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1943 switch (BO->getOpcode()) {
1944 default:
1945 return;
1946 case(BO_PtrMemD):
1947 case(BO_PtrMemI):
1948 HandleValue(BO->getLHS());
1949 return;
1950 case(BO_Comma):
1951 HandleValue(BO->getRHS());
1952 return;
1953 }
1954 }
1955 }
1956
1957 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1958 if (E->getCastKind() == CK_LValueToRValue)
1959 HandleValue(E->getSubExpr());
1960
1961 Inherited::VisitImplicitCastExpr(E);
1962 }
1963
1964 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1965 Expr *Callee = E->getCallee();
1966 if (isa<MemberExpr>(Callee))
1967 HandleValue(Callee);
1968
1969 Inherited::VisitCXXMemberCallExpr(E);
1970 }
1971 };
1972 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1973 ValueDecl *VD) {
1974 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1975 }
1976} // namespace
1977
Richard Smith7a614d82011-06-11 17:19:42 +00001978/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001979/// in-class initializer for a non-static C++ class member, and after
1980/// instantiating an in-class initializer in a class template. Such actions
1981/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001982void
Richard Smithca523302012-06-10 03:12:00 +00001983Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001984 Expr *InitExpr) {
1985 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001986 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1987 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001988
1989 if (!InitExpr) {
1990 FD->setInvalidDecl();
1991 FD->removeInClassInitializer();
1992 return;
1993 }
1994
Peter Collingbournefef21892011-10-23 18:59:44 +00001995 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1996 FD->setInvalidDecl();
1997 FD->removeInClassInitializer();
1998 return;
1999 }
2000
Hans Wennborg471f9852012-09-18 15:58:06 +00002001 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2002 != DiagnosticsEngine::Ignored) {
2003 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2004 }
2005
Richard Smith7a614d82011-06-11 17:19:42 +00002006 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002007 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00002008 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002009 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00002010 << /*at end of ctor*/1 << InitExpr->getSourceRange();
2011 }
Sebastian Redl33deb352012-02-22 10:50:08 +00002012 Expr **Inits = &InitExpr;
2013 unsigned NumInits = 1;
2014 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002015 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002016 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002017 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002018 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2019 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002020 if (Init.isInvalid()) {
2021 FD->setInvalidDecl();
2022 return;
2023 }
Richard Smith7a614d82011-06-11 17:19:42 +00002024 }
2025
Richard Smith41956372013-01-14 22:39:08 +00002026 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002027 // The initialization of each base and member constitutes a
2028 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002029 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002030 if (Init.isInvalid()) {
2031 FD->setInvalidDecl();
2032 return;
2033 }
2034
2035 InitExpr = Init.release();
2036
2037 FD->setInClassInitializer(InitExpr);
2038}
2039
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002040/// \brief Find the direct and/or virtual base specifiers that
2041/// correspond to the given base type, for use in base initialization
2042/// within a constructor.
2043static bool FindBaseInitializer(Sema &SemaRef,
2044 CXXRecordDecl *ClassDecl,
2045 QualType BaseType,
2046 const CXXBaseSpecifier *&DirectBaseSpec,
2047 const CXXBaseSpecifier *&VirtualBaseSpec) {
2048 // First, check for a direct base class.
2049 DirectBaseSpec = 0;
2050 for (CXXRecordDecl::base_class_const_iterator Base
2051 = ClassDecl->bases_begin();
2052 Base != ClassDecl->bases_end(); ++Base) {
2053 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2054 // We found a direct base of this type. That's what we're
2055 // initializing.
2056 DirectBaseSpec = &*Base;
2057 break;
2058 }
2059 }
2060
2061 // Check for a virtual base class.
2062 // FIXME: We might be able to short-circuit this if we know in advance that
2063 // there are no virtual bases.
2064 VirtualBaseSpec = 0;
2065 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2066 // We haven't found a base yet; search the class hierarchy for a
2067 // virtual base class.
2068 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2069 /*DetectVirtual=*/false);
2070 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2071 BaseType, Paths)) {
2072 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2073 Path != Paths.end(); ++Path) {
2074 if (Path->back().Base->isVirtual()) {
2075 VirtualBaseSpec = Path->back().Base;
2076 break;
2077 }
2078 }
2079 }
2080 }
2081
2082 return DirectBaseSpec || VirtualBaseSpec;
2083}
2084
Sebastian Redl6df65482011-09-24 17:48:25 +00002085/// \brief Handle a C++ member initializer using braced-init-list syntax.
2086MemInitResult
2087Sema::ActOnMemInitializer(Decl *ConstructorD,
2088 Scope *S,
2089 CXXScopeSpec &SS,
2090 IdentifierInfo *MemberOrBase,
2091 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002092 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002093 SourceLocation IdLoc,
2094 Expr *InitList,
2095 SourceLocation EllipsisLoc) {
2096 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002097 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002098 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002099}
2100
2101/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002102MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002103Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002104 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002105 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002106 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002107 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002108 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002109 SourceLocation IdLoc,
2110 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002111 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002112 SourceLocation RParenLoc,
2113 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002114 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2115 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002116 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002117 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002118 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002119}
2120
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002121namespace {
2122
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002123// Callback to only accept typo corrections that can be a valid C++ member
2124// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002125class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2126 public:
2127 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2128 : ClassDecl(ClassDecl) {}
2129
2130 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2131 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2132 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2133 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2134 else
2135 return isa<TypeDecl>(ND);
2136 }
2137 return false;
2138 }
2139
2140 private:
2141 CXXRecordDecl *ClassDecl;
2142};
2143
2144}
2145
Sebastian Redl6df65482011-09-24 17:48:25 +00002146/// \brief Handle a C++ member initializer.
2147MemInitResult
2148Sema::BuildMemInitializer(Decl *ConstructorD,
2149 Scope *S,
2150 CXXScopeSpec &SS,
2151 IdentifierInfo *MemberOrBase,
2152 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002153 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002154 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002155 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002156 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002157 if (!ConstructorD)
2158 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002160 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002161
2162 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002163 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002164 if (!Constructor) {
2165 // The user wrote a constructor initializer on a function that is
2166 // not a C++ constructor. Ignore the error for now, because we may
2167 // have more member initializers coming; we'll diagnose it just
2168 // once in ActOnMemInitializers.
2169 return true;
2170 }
2171
2172 CXXRecordDecl *ClassDecl = Constructor->getParent();
2173
2174 // C++ [class.base.init]p2:
2175 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002176 // constructor's class and, if not found in that scope, are looked
2177 // up in the scope containing the constructor's definition.
2178 // [Note: if the constructor's class contains a member with the
2179 // same name as a direct or virtual base class of the class, a
2180 // mem-initializer-id naming the member or base class and composed
2181 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002182 // mem-initializer-id for the hidden base class may be specified
2183 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002184 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002185 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002186 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002187 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002188 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002189 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002190 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2191 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002192 if (EllipsisLoc.isValid())
2193 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002194 << MemberOrBase
2195 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002196
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002197 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002198 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002199 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002200 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002201 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002202 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002203 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002204
2205 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002206 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002207 } else if (DS.getTypeSpecType() == TST_decltype) {
2208 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002209 } else {
2210 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2211 LookupParsedName(R, S, &SS);
2212
2213 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2214 if (!TyD) {
2215 if (R.isAmbiguous()) return true;
2216
John McCallfd225442010-04-09 19:01:14 +00002217 // We don't want access-control diagnostics here.
2218 R.suppressDiagnostics();
2219
Douglas Gregor7a886e12010-01-19 06:46:48 +00002220 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2221 bool NotUnknownSpecialization = false;
2222 DeclContext *DC = computeDeclContext(SS, false);
2223 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2224 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2225
2226 if (!NotUnknownSpecialization) {
2227 // When the scope specifier can refer to a member of an unknown
2228 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002229 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2230 SS.getWithLocInContext(Context),
2231 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002232 if (BaseType.isNull())
2233 return true;
2234
Douglas Gregor7a886e12010-01-19 06:46:48 +00002235 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002236 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002237 }
2238 }
2239
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002240 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002241 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002242 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002243 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002244 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002245 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002246 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2247 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002248 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002249 // We have found a non-static data member with a similar
2250 // name to what was typed; complain and initialize that
2251 // member.
2252 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2253 << MemberOrBase << true << CorrectedQuotedStr
2254 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2255 Diag(Member->getLocation(), diag::note_previous_decl)
2256 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002257
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002258 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002259 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002260 const CXXBaseSpecifier *DirectBaseSpec;
2261 const CXXBaseSpecifier *VirtualBaseSpec;
2262 if (FindBaseInitializer(*this, ClassDecl,
2263 Context.getTypeDeclType(Type),
2264 DirectBaseSpec, VirtualBaseSpec)) {
2265 // We have found a direct or virtual base class with a
2266 // similar name to what was typed; complain and initialize
2267 // that base class.
2268 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002269 << MemberOrBase << false << CorrectedQuotedStr
2270 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002271
2272 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2273 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002274 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002275 diag::note_base_class_specified_here)
2276 << BaseSpec->getType()
2277 << BaseSpec->getSourceRange();
2278
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002279 TyD = Type;
2280 }
2281 }
2282 }
2283
Douglas Gregor7a886e12010-01-19 06:46:48 +00002284 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002285 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002286 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002287 return true;
2288 }
John McCall2b194412009-12-21 10:41:20 +00002289 }
2290
Douglas Gregor7a886e12010-01-19 06:46:48 +00002291 if (BaseType.isNull()) {
2292 BaseType = Context.getTypeDeclType(TyD);
2293 if (SS.isSet()) {
2294 NestedNameSpecifier *Qualifier =
2295 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002296
Douglas Gregor7a886e12010-01-19 06:46:48 +00002297 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002298 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002299 }
John McCall2b194412009-12-21 10:41:20 +00002300 }
2301 }
Mike Stump1eb44332009-09-09 15:08:12 +00002302
John McCalla93c9342009-12-07 02:54:59 +00002303 if (!TInfo)
2304 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002305
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002306 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002307}
2308
Chandler Carruth81c64772011-09-03 01:14:15 +00002309/// Checks a member initializer expression for cases where reference (or
2310/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002311static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2312 Expr *Init,
2313 SourceLocation IdLoc) {
2314 QualType MemberTy = Member->getType();
2315
2316 // We only handle pointers and references currently.
2317 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2318 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2319 return;
2320
2321 const bool IsPointer = MemberTy->isPointerType();
2322 if (IsPointer) {
2323 if (const UnaryOperator *Op
2324 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2325 // The only case we're worried about with pointers requires taking the
2326 // address.
2327 if (Op->getOpcode() != UO_AddrOf)
2328 return;
2329
2330 Init = Op->getSubExpr();
2331 } else {
2332 // We only handle address-of expression initializers for pointers.
2333 return;
2334 }
2335 }
2336
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002337 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2338 // Taking the address of a temporary will be diagnosed as a hard error.
2339 if (IsPointer)
2340 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002341
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002342 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2343 << Member << Init->getSourceRange();
2344 } else if (const DeclRefExpr *DRE
2345 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2346 // We only warn when referring to a non-reference parameter declaration.
2347 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2348 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002349 return;
2350
2351 S.Diag(Init->getExprLoc(),
2352 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2353 : diag::warn_bind_ref_member_to_parameter)
2354 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002355 } else {
2356 // Other initializers are fine.
2357 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002358 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002359
2360 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2361 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002362}
2363
John McCallf312b1e2010-08-26 23:41:50 +00002364MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002365Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002366 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002367 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2368 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2369 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002370 "Member must be a FieldDecl or IndirectFieldDecl");
2371
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002372 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002373 return true;
2374
Douglas Gregor464b2f02010-11-05 22:21:31 +00002375 if (Member->isInvalidDecl())
2376 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002377
John McCallb4190042009-11-04 23:02:40 +00002378 // Diagnose value-uses of fields to initialize themselves, e.g.
2379 // foo(foo)
2380 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002381 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002382 Expr **Args;
2383 unsigned NumArgs;
2384 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2385 Args = ParenList->getExprs();
2386 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002387 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002388 Args = InitList->getInits();
2389 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002390 } else {
2391 // Template instantiation doesn't reconstruct ParenListExprs for us.
2392 Args = &Init;
2393 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002395
Richard Trieude5e75c2012-06-14 23:11:34 +00002396 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2397 != DiagnosticsEngine::Ignored)
2398 for (unsigned i = 0; i < NumArgs; ++i)
2399 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002400 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002401 // initializing the i'th field, throw a warning if any of the >= i'th
2402 // fields are used, as they are not yet initialized.
2403 // Right now we are only handling the case where the i'th field uses
2404 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002405 // Also need to take into account that some fields may be initialized by
2406 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002407 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002408
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002409 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002410
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002411 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002412 // Can't check initialization for a member of dependent type or when
2413 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002414 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002415 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002416 bool InitList = false;
2417 if (isa<InitListExpr>(Init)) {
2418 InitList = true;
2419 Args = &Init;
2420 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002421
2422 if (isStdInitializerList(Member->getType(), 0)) {
2423 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2424 << /*at end of ctor*/1 << InitRange;
2425 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002426 }
2427
Chandler Carruth894aed92010-12-06 09:23:57 +00002428 // Initialize the member.
2429 InitializedEntity MemberEntity =
2430 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2431 : InitializedEntity::InitializeMember(IndirectMember, 0);
2432 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002433 InitList ? InitializationKind::CreateDirectList(IdLoc)
2434 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2435 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002436
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002437 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2438 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002439 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002440 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002441 if (MemberInit.isInvalid())
2442 return true;
2443
Richard Smith41956372013-01-14 22:39:08 +00002444 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002445 // The initialization of each base and member constitutes a
2446 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002447 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002448 if (MemberInit.isInvalid())
2449 return true;
2450
Richard Smithc83c2302012-12-19 01:39:02 +00002451 Init = MemberInit.get();
2452 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002453 }
2454
Chandler Carruth894aed92010-12-06 09:23:57 +00002455 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002456 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2457 InitRange.getBegin(), Init,
2458 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002459 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002460 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2461 InitRange.getBegin(), Init,
2462 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002463 }
Eli Friedman59c04372009-07-29 19:44:27 +00002464}
2465
John McCallf312b1e2010-08-26 23:41:50 +00002466MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002467Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002468 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002469 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002470 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002471 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002472 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002473 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002474
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002475 bool InitList = true;
2476 Expr **Args = &Init;
2477 unsigned NumArgs = 1;
2478 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2479 InitList = false;
2480 Args = ParenList->getExprs();
2481 NumArgs = ParenList->getNumExprs();
2482 }
2483
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002484 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002485 // Initialize the object.
2486 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2487 QualType(ClassDecl->getTypeForDecl(), 0));
2488 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002489 InitList ? InitializationKind::CreateDirectList(NameLoc)
2490 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2491 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002492 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2493 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002494 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002495 0);
Sean Hunt41717662011-02-26 19:13:13 +00002496 if (DelegationInit.isInvalid())
2497 return true;
2498
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002499 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2500 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002501
Richard Smith41956372013-01-14 22:39:08 +00002502 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002503 // The initialization of each base and member constitutes a
2504 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002505 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2506 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002507 if (DelegationInit.isInvalid())
2508 return true;
2509
Eli Friedmand21016f2012-05-19 23:35:23 +00002510 // If we are in a dependent context, template instantiation will
2511 // perform this type-checking again. Just save the arguments that we
2512 // received in a ParenListExpr.
2513 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2514 // of the information that we have about the base
2515 // initializer. However, deconstructing the ASTs is a dicey process,
2516 // and this approach is far more likely to get the corner cases right.
2517 if (CurContext->isDependentContext())
2518 DelegationInit = Owned(Init);
2519
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002520 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002521 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002522 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002523}
2524
2525MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002526Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002527 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002528 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002529 SourceLocation BaseLoc
2530 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002531
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002532 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2533 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2534 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2535
2536 // C++ [class.base.init]p2:
2537 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002538 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002539 // of that class, the mem-initializer is ill-formed. A
2540 // mem-initializer-list can initialize a base class using any
2541 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002542 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002543
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002544 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002545 if (EllipsisLoc.isValid()) {
2546 // This is a pack expansion.
2547 if (!BaseType->containsUnexpandedParameterPack()) {
2548 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002549 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002550
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002551 EllipsisLoc = SourceLocation();
2552 }
2553 } else {
2554 // Check for any unexpanded parameter packs.
2555 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2556 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002557
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002558 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002559 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002560 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002561
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002562 // Check for direct and virtual base classes.
2563 const CXXBaseSpecifier *DirectBaseSpec = 0;
2564 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2565 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002566 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2567 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002568 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002569
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002570 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2571 VirtualBaseSpec);
2572
2573 // C++ [base.class.init]p2:
2574 // Unless the mem-initializer-id names a nonstatic data member of the
2575 // constructor's class or a direct or virtual base of that class, the
2576 // mem-initializer is ill-formed.
2577 if (!DirectBaseSpec && !VirtualBaseSpec) {
2578 // If the class has any dependent bases, then it's possible that
2579 // one of those types will resolve to the same type as
2580 // BaseType. Therefore, just treat this as a dependent base
2581 // class initialization. FIXME: Should we try to check the
2582 // initialization anyway? It seems odd.
2583 if (ClassDecl->hasAnyDependentBases())
2584 Dependent = true;
2585 else
2586 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2587 << BaseType << Context.getTypeDeclType(ClassDecl)
2588 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2589 }
2590 }
2591
2592 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002593 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Sebastian Redl6df65482011-09-24 17:48:25 +00002595 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2596 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002597 InitRange.getBegin(), Init,
2598 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002599 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002600
2601 // C++ [base.class.init]p2:
2602 // If a mem-initializer-id is ambiguous because it designates both
2603 // a direct non-virtual base class and an inherited virtual base
2604 // class, the mem-initializer is ill-formed.
2605 if (DirectBaseSpec && VirtualBaseSpec)
2606 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002607 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002608
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002609 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002610 if (!BaseSpec)
2611 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2612
2613 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002614 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002615 Expr **Args = &Init;
2616 unsigned NumArgs = 1;
2617 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002618 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002619 Args = ParenList->getExprs();
2620 NumArgs = ParenList->getNumExprs();
2621 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002622
2623 InitializedEntity BaseEntity =
2624 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2625 InitializationKind Kind =
2626 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2627 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2628 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002629 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2630 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002631 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002632 if (BaseInit.isInvalid())
2633 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002634
Richard Smith41956372013-01-14 22:39:08 +00002635 // C++11 [class.base.init]p7:
2636 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002637 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002638 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002639 if (BaseInit.isInvalid())
2640 return true;
2641
2642 // If we are in a dependent context, template instantiation will
2643 // perform this type-checking again. Just save the arguments that we
2644 // received in a ParenListExpr.
2645 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2646 // of the information that we have about the base
2647 // initializer. However, deconstructing the ASTs is a dicey process,
2648 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002649 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002650 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002651
Sean Huntcbb67482011-01-08 20:30:50 +00002652 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002653 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002654 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002655 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002656 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002657}
2658
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002659// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002660static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2661 if (T.isNull()) T = E->getType();
2662 QualType TargetType = SemaRef.BuildReferenceType(
2663 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002664 SourceLocation ExprLoc = E->getLocStart();
2665 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2666 TargetType, ExprLoc);
2667
2668 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2669 SourceRange(ExprLoc, ExprLoc),
2670 E->getSourceRange()).take();
2671}
2672
Anders Carlssone5ef7402010-04-23 03:10:23 +00002673/// ImplicitInitializerKind - How an implicit base or member initializer should
2674/// initialize its base or member.
2675enum ImplicitInitializerKind {
2676 IIK_Default,
2677 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002678 IIK_Move,
2679 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002680};
2681
Anders Carlssondefefd22010-04-23 02:00:02 +00002682static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002683BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002684 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002685 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002686 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002687 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002688 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002689 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2690 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002691
John McCall60d7b3a2010-08-24 06:29:42 +00002692 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002693
2694 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002695 case IIK_Inherit: {
2696 const CXXRecordDecl *Inherited =
2697 Constructor->getInheritedConstructor()->getParent();
2698 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2699 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2700 // C++11 [class.inhctor]p8:
2701 // Each expression in the expression-list is of the form
2702 // static_cast<T&&>(p), where p is the name of the corresponding
2703 // constructor parameter and T is the declared type of p.
2704 SmallVector<Expr*, 16> Args;
2705 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2706 ParmVarDecl *PD = Constructor->getParamDecl(I);
2707 ExprResult ArgExpr =
2708 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2709 VK_LValue, SourceLocation());
2710 if (ArgExpr.isInvalid())
2711 return true;
2712 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2713 }
2714
2715 InitializationKind InitKind = InitializationKind::CreateDirect(
2716 Constructor->getLocation(), SourceLocation(), SourceLocation());
2717 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2718 Args.data(), Args.size());
2719 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2720 break;
2721 }
2722 }
2723 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002724 case IIK_Default: {
2725 InitializationKind InitKind
2726 = InitializationKind::CreateDefault(Constructor->getLocation());
2727 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002728 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002729 break;
2730 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002731
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002732 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002733 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002734 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002735 ParmVarDecl *Param = Constructor->getParamDecl(0);
2736 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002737
Anders Carlssone5ef7402010-04-23 03:10:23 +00002738 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002739 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002740 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002741 Constructor->getLocation(), ParamType,
2742 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002743
Eli Friedman5f2987c2012-02-02 03:46:19 +00002744 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2745
Anders Carlssonc7957502010-04-24 22:02:54 +00002746 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002747 QualType ArgTy =
2748 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2749 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002750
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002751 if (Moving) {
2752 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2753 }
2754
John McCallf871d0c2010-08-07 06:22:56 +00002755 CXXCastPath BasePath;
2756 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002757 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2758 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002759 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002760 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002761
Anders Carlssone5ef7402010-04-23 03:10:23 +00002762 InitializationKind InitKind
2763 = InitializationKind::CreateDirect(Constructor->getLocation(),
2764 SourceLocation(), SourceLocation());
2765 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2766 &CopyCtorArg, 1);
2767 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002768 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002769 break;
2770 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002771 }
John McCall9ae2f072010-08-23 23:25:46 +00002772
Douglas Gregor53c374f2010-12-07 00:41:46 +00002773 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002774 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002775 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002776
Anders Carlssondefefd22010-04-23 02:00:02 +00002777 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002778 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002779 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2780 SourceLocation()),
2781 BaseSpec->isVirtual(),
2782 SourceLocation(),
2783 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002784 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002785 SourceLocation());
2786
Anders Carlssondefefd22010-04-23 02:00:02 +00002787 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002788}
2789
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002790static bool RefersToRValueRef(Expr *MemRef) {
2791 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2792 return Referenced->getType()->isRValueReferenceType();
2793}
2794
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002795static bool
2796BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002797 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002798 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002799 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002800 if (Field->isInvalidDecl())
2801 return true;
2802
Chandler Carruthf186b542010-06-29 23:50:44 +00002803 SourceLocation Loc = Constructor->getLocation();
2804
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002805 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2806 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002807 ParmVarDecl *Param = Constructor->getParamDecl(0);
2808 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002809
2810 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002811 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2812 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002813
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002814 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002815 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002816 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002817 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002818
Eli Friedman5f2987c2012-02-02 03:46:19 +00002819 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2820
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002821 if (Moving) {
2822 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2823 }
2824
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002825 // Build a reference to this field within the parameter.
2826 CXXScopeSpec SS;
2827 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2828 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002829 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2830 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002831 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002832 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002833 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002834 ParamType, Loc,
2835 /*IsArrow=*/false,
2836 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002837 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002838 /*FirstQualifierInScope=*/0,
2839 MemberLookup,
2840 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002842 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002843
2844 // C++11 [class.copy]p15:
2845 // - if a member m has rvalue reference type T&&, it is direct-initialized
2846 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002847 if (RefersToRValueRef(CtorArg.get())) {
2848 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002849 }
2850
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002851 // When the field we are copying is an array, create index variables for
2852 // each dimension of the array. We use these index variables to subscript
2853 // the source array, and other clients (e.g., CodeGen) will perform the
2854 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002855 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002856 QualType BaseType = Field->getType();
2857 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002858 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002859 while (const ConstantArrayType *Array
2860 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002861 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002862 // Create the iteration variable for this array index.
2863 IdentifierInfo *IterationVarName = 0;
2864 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002865 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002866 llvm::raw_svector_ostream OS(Str);
2867 OS << "__i" << IndexVariables.size();
2868 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2869 }
2870 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002871 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002872 IterationVarName, SizeType,
2873 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002874 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002875 IndexVariables.push_back(IterationVar);
2876
2877 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002878 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002879 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002880 assert(!IterationVarRef.isInvalid() &&
2881 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002882 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2883 assert(!IterationVarRef.isInvalid() &&
2884 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002885
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002886 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002887 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002888 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002889 Loc);
2890 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002891 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002892
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002893 BaseType = Array->getElementType();
2894 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002895
2896 // The array subscript expression is an lvalue, which is wrong for moving.
2897 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002898 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002899
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002900 // Construct the entity that we will be initializing. For an array, this
2901 // will be first element in the array, which may require several levels
2902 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002903 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002904 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002905 if (Indirect)
2906 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2907 else
2908 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002909 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2910 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2911 0,
2912 Entities.back()));
2913
2914 // Direct-initialize to use the copy constructor.
2915 InitializationKind InitKind =
2916 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2917
Sebastian Redl74e611a2011-09-04 18:14:28 +00002918 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002919 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002920 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002921
John McCall60d7b3a2010-08-24 06:29:42 +00002922 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002923 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002924 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002925 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002926 if (MemberInit.isInvalid())
2927 return true;
2928
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002929 if (Indirect) {
2930 assert(IndexVariables.size() == 0 &&
2931 "Indirect field improperly initialized");
2932 CXXMemberInit
2933 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2934 Loc, Loc,
2935 MemberInit.takeAs<Expr>(),
2936 Loc);
2937 } else
2938 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2939 Loc, MemberInit.takeAs<Expr>(),
2940 Loc,
2941 IndexVariables.data(),
2942 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002943 return false;
2944 }
2945
Richard Smith07b0fdc2013-03-18 21:12:30 +00002946 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2947 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002948
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002949 QualType FieldBaseElementType =
2950 SemaRef.Context.getBaseElementType(Field->getType());
2951
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002952 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002953 InitializedEntity InitEntity
2954 = Indirect? InitializedEntity::InitializeMember(Indirect)
2955 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002956 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002957 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002958
2959 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002960 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002961 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002962
Douglas Gregor53c374f2010-12-07 00:41:46 +00002963 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002964 if (MemberInit.isInvalid())
2965 return true;
2966
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002967 if (Indirect)
2968 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2969 Indirect, Loc,
2970 Loc,
2971 MemberInit.get(),
2972 Loc);
2973 else
2974 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2975 Field, Loc, Loc,
2976 MemberInit.get(),
2977 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002978 return false;
2979 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002980
Sean Hunt1f2f3842011-05-17 00:19:05 +00002981 if (!Field->getParent()->isUnion()) {
2982 if (FieldBaseElementType->isReferenceType()) {
2983 SemaRef.Diag(Constructor->getLocation(),
2984 diag::err_uninitialized_member_in_ctor)
2985 << (int)Constructor->isImplicit()
2986 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2987 << 0 << Field->getDeclName();
2988 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2989 return true;
2990 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002991
Sean Hunt1f2f3842011-05-17 00:19:05 +00002992 if (FieldBaseElementType.isConstQualified()) {
2993 SemaRef.Diag(Constructor->getLocation(),
2994 diag::err_uninitialized_member_in_ctor)
2995 << (int)Constructor->isImplicit()
2996 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2997 << 1 << Field->getDeclName();
2998 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2999 return true;
3000 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003001 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003002
David Blaikie4e4d0842012-03-11 07:00:24 +00003003 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003004 FieldBaseElementType->isObjCRetainableType() &&
3005 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3006 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003007 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003008 // Default-initialize Objective-C pointers to NULL.
3009 CXXMemberInit
3010 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3011 Loc, Loc,
3012 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3013 Loc);
3014 return false;
3015 }
3016
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003017 // Nothing to initialize.
3018 CXXMemberInit = 0;
3019 return false;
3020}
John McCallf1860e52010-05-20 23:23:51 +00003021
3022namespace {
3023struct BaseAndFieldInfo {
3024 Sema &S;
3025 CXXConstructorDecl *Ctor;
3026 bool AnyErrorsInInits;
3027 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003028 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003029 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003030
3031 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3032 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003033 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3034 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003035 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003036 else if (Generated && Ctor->isMoveConstructor())
3037 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003038 else if (Ctor->getInheritedConstructor())
3039 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003040 else
3041 IIK = IIK_Default;
3042 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003043
3044 bool isImplicitCopyOrMove() const {
3045 switch (IIK) {
3046 case IIK_Copy:
3047 case IIK_Move:
3048 return true;
3049
3050 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003051 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003052 return false;
3053 }
David Blaikie30263482012-01-20 21:50:17 +00003054
3055 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003056 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003057
3058 bool addFieldInitializer(CXXCtorInitializer *Init) {
3059 AllToInit.push_back(Init);
3060
3061 // Check whether this initializer makes the field "used".
3062 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3063 S.UnusedPrivateFields.remove(Init->getAnyMember());
3064
3065 return false;
3066 }
John McCallf1860e52010-05-20 23:23:51 +00003067};
3068}
3069
Richard Smitha4950662011-09-19 13:34:43 +00003070/// \brief Determine whether the given indirect field declaration is somewhere
3071/// within an anonymous union.
3072static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3073 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3074 CEnd = F->chain_end();
3075 C != CEnd; ++C)
3076 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3077 if (Record->isUnion())
3078 return true;
3079
3080 return false;
3081}
3082
Douglas Gregorddb21472011-11-02 23:04:16 +00003083/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3084/// array type.
3085static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3086 if (T->isIncompleteArrayType())
3087 return true;
3088
3089 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3090 if (!ArrayT->getSize())
3091 return true;
3092
3093 T = ArrayT->getElementType();
3094 }
3095
3096 return false;
3097}
3098
Richard Smith7a614d82011-06-11 17:19:42 +00003099static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003100 FieldDecl *Field,
3101 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003102
Chandler Carruthe861c602010-06-30 02:59:29 +00003103 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003104 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3105 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003106
Richard Smith0b8220a2012-08-07 21:30:42 +00003107 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003108 // has a brace-or-equal-initializer, the entity is initialized as specified
3109 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003110 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003111 CXXCtorInitializer *Init;
3112 if (Indirect)
3113 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3114 SourceLocation(),
3115 SourceLocation(), 0,
3116 SourceLocation());
3117 else
3118 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3119 SourceLocation(),
3120 SourceLocation(), 0,
3121 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003122 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003123 }
3124
Richard Smithc115f632011-09-18 11:14:50 +00003125 // Don't build an implicit initializer for union members if none was
3126 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003127 if (Field->getParent()->isUnion() ||
3128 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003129 return false;
3130
Douglas Gregorddb21472011-11-02 23:04:16 +00003131 // Don't initialize incomplete or zero-length arrays.
3132 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3133 return false;
3134
John McCallf1860e52010-05-20 23:23:51 +00003135 // Don't try to build an implicit initializer if there were semantic
3136 // errors in any of the initializers (and therefore we might be
3137 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003138 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003139 return false;
3140
Sean Huntcbb67482011-01-08 20:30:50 +00003141 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003142 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3143 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003144 return true;
John McCallf1860e52010-05-20 23:23:51 +00003145
Richard Smith0b8220a2012-08-07 21:30:42 +00003146 if (!Init)
3147 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003148
Richard Smith0b8220a2012-08-07 21:30:42 +00003149 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003150}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003151
3152bool
3153Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3154 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003155 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003156 Constructor->setNumCtorInitializers(1);
3157 CXXCtorInitializer **initializer =
3158 new (Context) CXXCtorInitializer*[1];
3159 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3160 Constructor->setCtorInitializers(initializer);
3161
Sean Huntb76af9c2011-05-03 23:05:34 +00003162 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003163 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003164 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3165 }
3166
Sean Huntc1598702011-05-05 00:05:47 +00003167 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003168
Sean Hunt059ce0d2011-05-01 07:04:31 +00003169 return false;
3170}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003171
David Blaikie93c86172013-01-17 05:26:25 +00003172bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3173 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003174 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003175 // Just store the initializers as written, they will be checked during
3176 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003177 if (!Initializers.empty()) {
3178 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003179 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003180 new (Context) CXXCtorInitializer*[Initializers.size()];
3181 memcpy(baseOrMemberInitializers, Initializers.data(),
3182 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003183 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003184 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003185
3186 // Let template instantiation know whether we had errors.
3187 if (AnyErrors)
3188 Constructor->setInvalidDecl();
3189
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003190 return false;
3191 }
3192
John McCallf1860e52010-05-20 23:23:51 +00003193 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003194
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003195 // We need to build the initializer AST according to order of construction
3196 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003197 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003198 if (!ClassDecl)
3199 return true;
3200
Eli Friedman80c30da2009-11-09 19:20:36 +00003201 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003202
David Blaikie93c86172013-01-17 05:26:25 +00003203 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003204 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003205
3206 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003207 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003208 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003209 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003210 }
3211
Anders Carlsson711f34a2010-04-21 19:52:01 +00003212 // Keep track of the direct virtual bases.
3213 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3214 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3215 E = ClassDecl->bases_end(); I != E; ++I) {
3216 if (I->isVirtual())
3217 DirectVBases.insert(I);
3218 }
3219
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003220 // Push virtual bases before others.
3221 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3222 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3223
Sean Huntcbb67482011-01-08 20:30:50 +00003224 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003225 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3226 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003227 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003228 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003229 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003230 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003231 VBase, IsInheritedVirtualBase,
3232 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003233 HadError = true;
3234 continue;
3235 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003236
John McCallf1860e52010-05-20 23:23:51 +00003237 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003238 }
3239 }
Mike Stump1eb44332009-09-09 15:08:12 +00003240
John McCallf1860e52010-05-20 23:23:51 +00003241 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003242 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3243 E = ClassDecl->bases_end(); Base != E; ++Base) {
3244 // Virtuals are in the virtual base list and already constructed.
3245 if (Base->isVirtual())
3246 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Sean Huntcbb67482011-01-08 20:30:50 +00003248 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003249 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3250 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003251 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003252 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003253 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003254 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003255 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003256 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003257 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003258 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003259
John McCallf1860e52010-05-20 23:23:51 +00003260 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003261 }
3262 }
Mike Stump1eb44332009-09-09 15:08:12 +00003263
John McCallf1860e52010-05-20 23:23:51 +00003264 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003265 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3266 MemEnd = ClassDecl->decls_end();
3267 Mem != MemEnd; ++Mem) {
3268 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003269 // C++ [class.bit]p2:
3270 // A declaration for a bit-field that omits the identifier declares an
3271 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3272 // initialized.
3273 if (F->isUnnamedBitfield())
3274 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003275
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003276 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003277 // handle anonymous struct/union fields based on their individual
3278 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003279 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003280 continue;
3281
3282 if (CollectFieldInitializer(*this, Info, F))
3283 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003284 continue;
3285 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003286
3287 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003288 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003289 continue;
3290
3291 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3292 if (F->getType()->isIncompleteArrayType()) {
3293 assert(ClassDecl->hasFlexibleArrayMember() &&
3294 "Incomplete array type is not valid");
3295 continue;
3296 }
3297
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003298 // Initialize each field of an anonymous struct individually.
3299 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3300 HadError = true;
3301
3302 continue;
3303 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003304 }
Mike Stump1eb44332009-09-09 15:08:12 +00003305
David Blaikie93c86172013-01-17 05:26:25 +00003306 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003307 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003308 Constructor->setNumCtorInitializers(NumInitializers);
3309 CXXCtorInitializer **baseOrMemberInitializers =
3310 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003311 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003312 NumInitializers * sizeof(CXXCtorInitializer*));
3313 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003314
John McCallef027fe2010-03-16 21:39:52 +00003315 // Constructors implicitly reference the base and member
3316 // destructors.
3317 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3318 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003319 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003320
3321 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003322}
3323
David Blaikieee000bb2013-01-17 08:49:22 +00003324static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003325 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003326 const RecordDecl *RD = RT->getDecl();
3327 if (RD->isAnonymousStructOrUnion()) {
3328 for (RecordDecl::field_iterator Field = RD->field_begin(),
3329 E = RD->field_end(); Field != E; ++Field)
3330 PopulateKeysForFields(*Field, IdealInits);
3331 return;
3332 }
Eli Friedman6347f422009-07-21 19:28:10 +00003333 }
David Blaikieee000bb2013-01-17 08:49:22 +00003334 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003335}
3336
Anders Carlssonea356fb2010-04-02 05:42:15 +00003337static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003338 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003339}
3340
Anders Carlssonea356fb2010-04-02 05:42:15 +00003341static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003342 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003343 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003344 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003345
David Blaikieee000bb2013-01-17 08:49:22 +00003346 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003347}
3348
David Blaikie93c86172013-01-17 05:26:25 +00003349static void DiagnoseBaseOrMemInitializerOrder(
3350 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3351 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003352 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003353 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003354
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003355 // Don't check initializers order unless the warning is enabled at the
3356 // location of at least one initializer.
3357 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003358 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003359 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003360 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3361 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003362 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003363 ShouldCheckOrder = true;
3364 break;
3365 }
3366 }
3367 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003368 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003369
John McCalld6ca8da2010-04-10 07:37:23 +00003370 // Build the list of bases and members in the order that they'll
3371 // actually be initialized. The explicit initializers should be in
3372 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003373 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Anders Carlsson071d6102010-04-02 03:38:04 +00003375 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3376
John McCalld6ca8da2010-04-10 07:37:23 +00003377 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003378 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003379 ClassDecl->vbases_begin(),
3380 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003381 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003382
John McCalld6ca8da2010-04-10 07:37:23 +00003383 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003384 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003385 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003386 if (Base->isVirtual())
3387 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003388 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003389 }
Mike Stump1eb44332009-09-09 15:08:12 +00003390
John McCalld6ca8da2010-04-10 07:37:23 +00003391 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003392 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003393 E = ClassDecl->field_end(); Field != E; ++Field) {
3394 if (Field->isUnnamedBitfield())
3395 continue;
3396
David Blaikieee000bb2013-01-17 08:49:22 +00003397 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003398 }
3399
John McCalld6ca8da2010-04-10 07:37:23 +00003400 unsigned NumIdealInits = IdealInitKeys.size();
3401 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003402
Sean Huntcbb67482011-01-08 20:30:50 +00003403 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003404 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003405 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003406 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003407
3408 // Scan forward to try to find this initializer in the idealized
3409 // initializers list.
3410 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3411 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003412 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003413
3414 // If we didn't find this initializer, it must be because we
3415 // scanned past it on a previous iteration. That can only
3416 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003417 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003418 Sema::SemaDiagnosticBuilder D =
3419 SemaRef.Diag(PrevInit->getSourceLocation(),
3420 diag::warn_initializer_out_of_order);
3421
Francois Pichet00eb3f92010-12-04 09:14:42 +00003422 if (PrevInit->isAnyMemberInitializer())
3423 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003424 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003425 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003426
Francois Pichet00eb3f92010-12-04 09:14:42 +00003427 if (Init->isAnyMemberInitializer())
3428 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003429 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003430 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003431
3432 // Move back to the initializer's location in the ideal list.
3433 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3434 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003435 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003436
3437 assert(IdealIndex != NumIdealInits &&
3438 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003439 }
John McCalld6ca8da2010-04-10 07:37:23 +00003440
3441 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003442 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003443}
3444
John McCall3c3ccdb2010-04-10 09:28:51 +00003445namespace {
3446bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003447 CXXCtorInitializer *Init,
3448 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003449 if (!PrevInit) {
3450 PrevInit = Init;
3451 return false;
3452 }
3453
Douglas Gregordc392c12013-03-25 23:28:23 +00003454 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003455 S.Diag(Init->getSourceLocation(),
3456 diag::err_multiple_mem_initialization)
3457 << Field->getDeclName()
3458 << Init->getSourceRange();
3459 else {
John McCallf4c73712011-01-19 06:33:43 +00003460 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003461 assert(BaseClass && "neither field nor base");
3462 S.Diag(Init->getSourceLocation(),
3463 diag::err_multiple_base_initialization)
3464 << QualType(BaseClass, 0)
3465 << Init->getSourceRange();
3466 }
3467 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3468 << 0 << PrevInit->getSourceRange();
3469
3470 return true;
3471}
3472
Sean Huntcbb67482011-01-08 20:30:50 +00003473typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003474typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3475
3476bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003477 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003478 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003479 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003480 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003481 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003482
3483 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003484 if (Parent->isUnion()) {
3485 UnionEntry &En = Unions[Parent];
3486 if (En.first && En.first != Child) {
3487 S.Diag(Init->getSourceLocation(),
3488 diag::err_multiple_mem_union_initialization)
3489 << Field->getDeclName()
3490 << Init->getSourceRange();
3491 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3492 << 0 << En.second->getSourceRange();
3493 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003494 }
3495 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003496 En.first = Child;
3497 En.second = Init;
3498 }
David Blaikie6fe29652011-11-17 06:01:57 +00003499 if (!Parent->isAnonymousStructOrUnion())
3500 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003501 }
3502
3503 Child = Parent;
3504 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003505 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003506
3507 return false;
3508}
3509}
3510
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003511/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003512void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003513 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003514 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003515 bool AnyErrors) {
3516 if (!ConstructorDecl)
3517 return;
3518
3519 AdjustDeclIfTemplate(ConstructorDecl);
3520
3521 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003522 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003523
3524 if (!Constructor) {
3525 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3526 return;
3527 }
3528
John McCall3c3ccdb2010-04-10 09:28:51 +00003529 // Mapping for the duplicate initializers check.
3530 // For member initializers, this is keyed with a FieldDecl*.
3531 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003532 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003533
3534 // Mapping for the inconsistent anonymous-union initializers check.
3535 RedundantUnionMap MemberUnions;
3536
Anders Carlssonea356fb2010-04-02 05:42:15 +00003537 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003538 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003539 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003540
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003541 // Set the source order index.
3542 Init->setSourceOrder(i);
3543
Francois Pichet00eb3f92010-12-04 09:14:42 +00003544 if (Init->isAnyMemberInitializer()) {
3545 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003546 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3547 CheckRedundantUnionInit(*this, Init, MemberUnions))
3548 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003549 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003550 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3551 if (CheckRedundantInit(*this, Init, Members[Key]))
3552 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003553 } else {
3554 assert(Init->isDelegatingInitializer());
3555 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003556 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003557 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003558 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003559 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003560 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003561 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003562 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003563 // Return immediately as the initializer is set.
3564 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003565 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003566 }
3567
Anders Carlssonea356fb2010-04-02 05:42:15 +00003568 if (HadError)
3569 return;
3570
David Blaikie93c86172013-01-17 05:26:25 +00003571 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003572
David Blaikie93c86172013-01-17 05:26:25 +00003573 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003574}
3575
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003576void
John McCallef027fe2010-03-16 21:39:52 +00003577Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3578 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003579 // Ignore dependent contexts. Also ignore unions, since their members never
3580 // have destructors implicitly called.
3581 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003582 return;
John McCall58e6f342010-03-16 05:22:47 +00003583
3584 // FIXME: all the access-control diagnostics are positioned on the
3585 // field/base declaration. That's probably good; that said, the
3586 // user might reasonably want to know why the destructor is being
3587 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003588
Anders Carlsson9f853df2009-11-17 04:44:12 +00003589 // Non-static data members.
3590 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3591 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003592 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003593 if (Field->isInvalidDecl())
3594 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003595
3596 // Don't destroy incomplete or zero-length arrays.
3597 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3598 continue;
3599
Anders Carlsson9f853df2009-11-17 04:44:12 +00003600 QualType FieldType = Context.getBaseElementType(Field->getType());
3601
3602 const RecordType* RT = FieldType->getAs<RecordType>();
3603 if (!RT)
3604 continue;
3605
3606 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003607 if (FieldClassDecl->isInvalidDecl())
3608 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003609 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003610 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003611 // The destructor for an implicit anonymous union member is never invoked.
3612 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3613 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003614
Douglas Gregordb89f282010-07-01 22:47:18 +00003615 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003616 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003617 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003618 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003619 << Field->getDeclName()
3620 << FieldType);
3621
Eli Friedman5f2987c2012-02-02 03:46:19 +00003622 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003623 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003624 }
3625
John McCall58e6f342010-03-16 05:22:47 +00003626 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3627
Anders Carlsson9f853df2009-11-17 04:44:12 +00003628 // Bases.
3629 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3630 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003631 // Bases are always records in a well-formed non-dependent class.
3632 const RecordType *RT = Base->getType()->getAs<RecordType>();
3633
3634 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003635 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003636 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003637
John McCall58e6f342010-03-16 05:22:47 +00003638 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003639 // If our base class is invalid, we probably can't get its dtor anyway.
3640 if (BaseClassDecl->isInvalidDecl())
3641 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003642 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003643 continue;
John McCall58e6f342010-03-16 05:22:47 +00003644
Douglas Gregordb89f282010-07-01 22:47:18 +00003645 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003646 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003647
3648 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003649 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003650 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003651 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003652 << Base->getSourceRange(),
3653 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003654
Eli Friedman5f2987c2012-02-02 03:46:19 +00003655 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003656 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003657 }
3658
3659 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003660 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3661 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003662
3663 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003664 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003665
3666 // Ignore direct virtual bases.
3667 if (DirectVirtualBases.count(RT))
3668 continue;
3669
John McCall58e6f342010-03-16 05:22:47 +00003670 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003671 // If our base class is invalid, we probably can't get its dtor anyway.
3672 if (BaseClassDecl->isInvalidDecl())
3673 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003674 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003675 continue;
John McCall58e6f342010-03-16 05:22:47 +00003676
Douglas Gregordb89f282010-07-01 22:47:18 +00003677 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003678 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003679 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003680 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003681 << VBase->getType(),
3682 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003683
Eli Friedman5f2987c2012-02-02 03:46:19 +00003684 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003685 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003686 }
3687}
3688
John McCalld226f652010-08-21 09:40:31 +00003689void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003690 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003691 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Mike Stump1eb44332009-09-09 15:08:12 +00003693 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003694 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003695 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003696}
3697
Mike Stump1eb44332009-09-09 15:08:12 +00003698bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003699 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003700 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3701 unsigned DiagID;
3702 AbstractDiagSelID SelID;
3703
3704 public:
3705 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3706 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3707
3708 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003709 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003710 if (SelID == -1)
3711 S.Diag(Loc, DiagID) << T;
3712 else
3713 S.Diag(Loc, DiagID) << SelID << T;
3714 }
3715 } Diagnoser(DiagID, SelID);
3716
3717 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003718}
3719
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003720bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003721 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003722 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003723 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Anders Carlsson11f21a02009-03-23 19:10:31 +00003725 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003726 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003727
Ted Kremenek6217b802009-07-29 21:53:49 +00003728 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003729 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003730 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003731 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003733 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003734 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003735 }
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Ted Kremenek6217b802009-07-29 21:53:49 +00003737 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003738 if (!RT)
3739 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003740
John McCall86ff3082010-02-04 22:26:26 +00003741 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003742
John McCall94c3b562010-08-18 09:41:07 +00003743 // We can't answer whether something is abstract until it has a
3744 // definition. If it's currently being defined, we'll walk back
3745 // over all the declarations when we have a full definition.
3746 const CXXRecordDecl *Def = RD->getDefinition();
3747 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003748 return false;
3749
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003750 if (!RD->isAbstract())
3751 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003753 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003754 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003755
John McCall94c3b562010-08-18 09:41:07 +00003756 return true;
3757}
3758
3759void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3760 // Check if we've already emitted the list of pure virtual functions
3761 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003762 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003763 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003765 CXXFinalOverriderMap FinalOverriders;
3766 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003767
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003768 // Keep a set of seen pure methods so we won't diagnose the same method
3769 // more than once.
3770 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3771
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003772 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3773 MEnd = FinalOverriders.end();
3774 M != MEnd;
3775 ++M) {
3776 for (OverridingMethods::iterator SO = M->second.begin(),
3777 SOEnd = M->second.end();
3778 SO != SOEnd; ++SO) {
3779 // C++ [class.abstract]p4:
3780 // A class is abstract if it contains or inherits at least one
3781 // pure virtual function for which the final overrider is pure
3782 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003784 //
3785 if (SO->second.size() != 1)
3786 continue;
3787
3788 if (!SO->second.front().Method->isPure())
3789 continue;
3790
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003791 if (!SeenPureMethods.insert(SO->second.front().Method))
3792 continue;
3793
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003794 Diag(SO->second.front().Method->getLocation(),
3795 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003796 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003797 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003798 }
3799
3800 if (!PureVirtualClassDiagSet)
3801 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3802 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003803}
3804
Anders Carlsson8211eff2009-03-24 01:19:16 +00003805namespace {
John McCall94c3b562010-08-18 09:41:07 +00003806struct AbstractUsageInfo {
3807 Sema &S;
3808 CXXRecordDecl *Record;
3809 CanQualType AbstractType;
3810 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003811
John McCall94c3b562010-08-18 09:41:07 +00003812 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3813 : S(S), Record(Record),
3814 AbstractType(S.Context.getCanonicalType(
3815 S.Context.getTypeDeclType(Record))),
3816 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003817
John McCall94c3b562010-08-18 09:41:07 +00003818 void DiagnoseAbstractType() {
3819 if (Invalid) return;
3820 S.DiagnoseAbstractType(Record);
3821 Invalid = true;
3822 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003823
John McCall94c3b562010-08-18 09:41:07 +00003824 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3825};
3826
3827struct CheckAbstractUsage {
3828 AbstractUsageInfo &Info;
3829 const NamedDecl *Ctx;
3830
3831 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3832 : Info(Info), Ctx(Ctx) {}
3833
3834 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3835 switch (TL.getTypeLocClass()) {
3836#define ABSTRACT_TYPELOC(CLASS, PARENT)
3837#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003838 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003839#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003840 }
John McCall94c3b562010-08-18 09:41:07 +00003841 }
Mike Stump1eb44332009-09-09 15:08:12 +00003842
John McCall94c3b562010-08-18 09:41:07 +00003843 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3844 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3845 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003846 if (!TL.getArg(I))
3847 continue;
3848
John McCall94c3b562010-08-18 09:41:07 +00003849 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3850 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003851 }
John McCall94c3b562010-08-18 09:41:07 +00003852 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003853
John McCall94c3b562010-08-18 09:41:07 +00003854 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3855 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
John McCall94c3b562010-08-18 09:41:07 +00003858 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3859 // Visit the type parameters from a permissive context.
3860 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3861 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3862 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3863 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3864 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3865 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003866 }
John McCall94c3b562010-08-18 09:41:07 +00003867 }
Mike Stump1eb44332009-09-09 15:08:12 +00003868
John McCall94c3b562010-08-18 09:41:07 +00003869 // Visit pointee types from a permissive context.
3870#define CheckPolymorphic(Type) \
3871 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3872 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3873 }
3874 CheckPolymorphic(PointerTypeLoc)
3875 CheckPolymorphic(ReferenceTypeLoc)
3876 CheckPolymorphic(MemberPointerTypeLoc)
3877 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003878 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003879
John McCall94c3b562010-08-18 09:41:07 +00003880 /// Handle all the types we haven't given a more specific
3881 /// implementation for above.
3882 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3883 // Every other kind of type that we haven't called out already
3884 // that has an inner type is either (1) sugar or (2) contains that
3885 // inner type in some way as a subobject.
3886 if (TypeLoc Next = TL.getNextTypeLoc())
3887 return Visit(Next, Sel);
3888
3889 // If there's no inner type and we're in a permissive context,
3890 // don't diagnose.
3891 if (Sel == Sema::AbstractNone) return;
3892
3893 // Check whether the type matches the abstract type.
3894 QualType T = TL.getType();
3895 if (T->isArrayType()) {
3896 Sel = Sema::AbstractArrayType;
3897 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003898 }
John McCall94c3b562010-08-18 09:41:07 +00003899 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3900 if (CT != Info.AbstractType) return;
3901
3902 // It matched; do some magic.
3903 if (Sel == Sema::AbstractArrayType) {
3904 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3905 << T << TL.getSourceRange();
3906 } else {
3907 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3908 << Sel << T << TL.getSourceRange();
3909 }
3910 Info.DiagnoseAbstractType();
3911 }
3912};
3913
3914void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3915 Sema::AbstractDiagSelID Sel) {
3916 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3917}
3918
3919}
3920
3921/// Check for invalid uses of an abstract type in a method declaration.
3922static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3923 CXXMethodDecl *MD) {
3924 // No need to do the check on definitions, which require that
3925 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003926 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003927 return;
3928
3929 // For safety's sake, just ignore it if we don't have type source
3930 // information. This should never happen for non-implicit methods,
3931 // but...
3932 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3933 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3934}
3935
3936/// Check for invalid uses of an abstract type within a class definition.
3937static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3938 CXXRecordDecl *RD) {
3939 for (CXXRecordDecl::decl_iterator
3940 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3941 Decl *D = *I;
3942 if (D->isImplicit()) continue;
3943
3944 // Methods and method templates.
3945 if (isa<CXXMethodDecl>(D)) {
3946 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3947 } else if (isa<FunctionTemplateDecl>(D)) {
3948 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3949 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3950
3951 // Fields and static variables.
3952 } else if (isa<FieldDecl>(D)) {
3953 FieldDecl *FD = cast<FieldDecl>(D);
3954 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3955 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3956 } else if (isa<VarDecl>(D)) {
3957 VarDecl *VD = cast<VarDecl>(D);
3958 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3959 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3960
3961 // Nested classes and class templates.
3962 } else if (isa<CXXRecordDecl>(D)) {
3963 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3964 } else if (isa<ClassTemplateDecl>(D)) {
3965 CheckAbstractClassUsage(Info,
3966 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3967 }
3968 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003969}
3970
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003971/// \brief Perform semantic checks on a class definition that has been
3972/// completing, introducing implicitly-declared members, checking for
3973/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003974void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003975 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003976 return;
3977
John McCall94c3b562010-08-18 09:41:07 +00003978 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3979 AbstractUsageInfo Info(*this, Record);
3980 CheckAbstractClassUsage(Info, Record);
3981 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003982
3983 // If this is not an aggregate type and has no user-declared constructor,
3984 // complain about any non-static data members of reference or const scalar
3985 // type, since they will never get initializers.
3986 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003987 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3988 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003989 bool Complained = false;
3990 for (RecordDecl::field_iterator F = Record->field_begin(),
3991 FEnd = Record->field_end();
3992 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003993 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003994 continue;
3995
Douglas Gregor325e5932010-04-15 00:00:53 +00003996 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003997 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003998 if (!Complained) {
3999 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4000 << Record->getTagKind() << Record;
4001 Complained = true;
4002 }
4003
4004 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4005 << F->getType()->isReferenceType()
4006 << F->getDeclName();
4007 }
4008 }
4009 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004010
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004011 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004012 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004013
4014 if (Record->getIdentifier()) {
4015 // C++ [class.mem]p13:
4016 // If T is the name of a class, then each of the following shall have a
4017 // name different from T:
4018 // - every member of every anonymous union that is a member of class T.
4019 //
4020 // C++ [class.mem]p14:
4021 // In addition, if class T has a user-declared constructor (12.1), every
4022 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004023 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4024 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4025 ++I) {
4026 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004027 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4028 isa<IndirectFieldDecl>(D)) {
4029 Diag(D->getLocation(), diag::err_member_name_of_class)
4030 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004031 break;
4032 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004033 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004034 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004035
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004036 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004037 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004038 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004039 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004040 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4041 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4042 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004043
David Blaikieb6b5b972012-09-21 03:21:07 +00004044 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4045 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4046 DiagnoseAbstractType(Record);
4047 }
4048
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004049 if (!Record->isDependentType()) {
4050 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4051 MEnd = Record->method_end();
4052 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004053 // See if a method overloads virtual methods in a base
4054 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004055 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004056 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004057
4058 // Check whether the explicitly-defaulted special members are valid.
4059 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4060 CheckExplicitlyDefaultedSpecialMember(*M);
4061
4062 // For an explicitly defaulted or deleted special member, we defer
4063 // determining triviality until the class is complete. That time is now!
4064 if (!M->isImplicit() && !M->isUserProvided()) {
4065 CXXSpecialMember CSM = getSpecialMember(*M);
4066 if (CSM != CXXInvalid) {
4067 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4068
4069 // Inform the class that we've finished declaring this member.
4070 Record->finishedDefaultedOrDeletedMember(*M);
4071 }
4072 }
4073 }
4074 }
4075
4076 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4077 // function that is not a constructor declares that member function to be
4078 // const. [...] The class of which that function is a member shall be
4079 // a literal type.
4080 //
4081 // If the class has virtual bases, any constexpr members will already have
4082 // been diagnosed by the checks performed on the member declaration, so
4083 // suppress this (less useful) diagnostic.
4084 //
4085 // We delay this until we know whether an explicitly-defaulted (or deleted)
4086 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004087 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004088 !Record->isLiteral() && !Record->getNumVBases()) {
4089 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4090 MEnd = Record->method_end();
4091 M != MEnd; ++M) {
4092 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4093 switch (Record->getTemplateSpecializationKind()) {
4094 case TSK_ImplicitInstantiation:
4095 case TSK_ExplicitInstantiationDeclaration:
4096 case TSK_ExplicitInstantiationDefinition:
4097 // If a template instantiates to a non-literal type, but its members
4098 // instantiate to constexpr functions, the template is technically
4099 // ill-formed, but we allow it for sanity.
4100 continue;
4101
4102 case TSK_Undeclared:
4103 case TSK_ExplicitSpecialization:
4104 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4105 diag::err_constexpr_method_non_literal);
4106 break;
4107 }
4108
4109 // Only produce one error per class.
4110 break;
4111 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004112 }
4113 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004114
Richard Smith07b0fdc2013-03-18 21:12:30 +00004115 // Declare inheriting constructors. We do this eagerly here because:
4116 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004117 // constructors from different classes.
4118 // - The lazy declaration of the other implicit constructors is so as to not
4119 // waste space and performance on classes that are not meant to be
4120 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004121 // have inheriting constructors.
4122 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004123}
4124
Richard Smith7756afa2012-06-10 05:43:50 +00004125/// Is the special member function which would be selected to perform the
4126/// specified operation on the specified class type a constexpr constructor?
4127static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4128 Sema::CXXSpecialMember CSM,
4129 bool ConstArg) {
4130 Sema::SpecialMemberOverloadResult *SMOR =
4131 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4132 false, false, false, false);
4133 if (!SMOR || !SMOR->getMethod())
4134 // A constructor we wouldn't select can't be "involved in initializing"
4135 // anything.
4136 return true;
4137 return SMOR->getMethod()->isConstexpr();
4138}
4139
4140/// Determine whether the specified special member function would be constexpr
4141/// if it were implicitly defined.
4142static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4143 Sema::CXXSpecialMember CSM,
4144 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004145 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004146 return false;
4147
4148 // C++11 [dcl.constexpr]p4:
4149 // In the definition of a constexpr constructor [...]
4150 switch (CSM) {
4151 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004152 // Since default constructor lookup is essentially trivial (and cannot
4153 // involve, for instance, template instantiation), we compute whether a
4154 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4155 //
4156 // This is important for performance; we need to know whether the default
4157 // constructor is constexpr to determine whether the type is a literal type.
4158 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4159
Richard Smith7756afa2012-06-10 05:43:50 +00004160 case Sema::CXXCopyConstructor:
4161 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004162 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004163 break;
4164
4165 case Sema::CXXCopyAssignment:
4166 case Sema::CXXMoveAssignment:
4167 case Sema::CXXDestructor:
4168 case Sema::CXXInvalid:
4169 return false;
4170 }
4171
4172 // -- if the class is a non-empty union, or for each non-empty anonymous
4173 // union member of a non-union class, exactly one non-static data member
4174 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004175 //
4176 // If we squint, this is guaranteed, since exactly one non-static data member
4177 // will be initialized (if the constructor isn't deleted), we just don't know
4178 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004179 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004180 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004181
4182 // -- the class shall not have any virtual base classes;
4183 if (ClassDecl->getNumVBases())
4184 return false;
4185
4186 // -- every constructor involved in initializing [...] base class
4187 // sub-objects shall be a constexpr constructor;
4188 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4189 BEnd = ClassDecl->bases_end();
4190 B != BEnd; ++B) {
4191 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4192 if (!BaseType) continue;
4193
4194 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4195 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4196 return false;
4197 }
4198
4199 // -- every constructor involved in initializing non-static data members
4200 // [...] shall be a constexpr constructor;
4201 // -- every non-static data member and base class sub-object shall be
4202 // initialized
4203 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4204 FEnd = ClassDecl->field_end();
4205 F != FEnd; ++F) {
4206 if (F->isInvalidDecl())
4207 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004208 if (const RecordType *RecordTy =
4209 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004210 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4211 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4212 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004213 }
4214 }
4215
4216 // All OK, it's constexpr!
4217 return true;
4218}
4219
Richard Smithb9d0b762012-07-27 04:22:15 +00004220static Sema::ImplicitExceptionSpecification
4221computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4222 switch (S.getSpecialMember(MD)) {
4223 case Sema::CXXDefaultConstructor:
4224 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4225 case Sema::CXXCopyConstructor:
4226 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4227 case Sema::CXXCopyAssignment:
4228 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4229 case Sema::CXXMoveConstructor:
4230 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4231 case Sema::CXXMoveAssignment:
4232 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4233 case Sema::CXXDestructor:
4234 return S.ComputeDefaultedDtorExceptionSpec(MD);
4235 case Sema::CXXInvalid:
4236 break;
4237 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004238 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4239 "only special members have implicit exception specs");
4240 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004241}
4242
Richard Smithdd25e802012-07-30 23:48:14 +00004243static void
4244updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4245 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4246 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4247 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004248 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4249 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004250}
4251
Richard Smithb9d0b762012-07-27 04:22:15 +00004252void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4253 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4254 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4255 return;
4256
Richard Smithdd25e802012-07-30 23:48:14 +00004257 // Evaluate the exception specification.
4258 ImplicitExceptionSpecification ExceptSpec =
4259 computeImplicitExceptionSpec(*this, Loc, MD);
4260
4261 // Update the type of the special member to use it.
4262 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4263
4264 // A user-provided destructor can be defined outside the class. When that
4265 // happens, be sure to update the exception specification on both
4266 // declarations.
4267 const FunctionProtoType *CanonicalFPT =
4268 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4269 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4270 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4271 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004272}
4273
Richard Smith3003e1d2012-05-15 04:39:51 +00004274void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4275 CXXRecordDecl *RD = MD->getParent();
4276 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004277
Richard Smith3003e1d2012-05-15 04:39:51 +00004278 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4279 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004280
4281 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004282 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004283 bool First = MD == MD->getCanonicalDecl();
4284
4285 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004286
4287 // C++11 [dcl.fct.def.default]p1:
4288 // A function that is explicitly defaulted shall
4289 // -- be a special member function (checked elsewhere),
4290 // -- have the same type (except for ref-qualifiers, and except that a
4291 // copy operation can take a non-const reference) as an implicit
4292 // declaration, and
4293 // -- not have default arguments.
4294 unsigned ExpectedParams = 1;
4295 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4296 ExpectedParams = 0;
4297 if (MD->getNumParams() != ExpectedParams) {
4298 // This also checks for default arguments: a copy or move constructor with a
4299 // default argument is classified as a default constructor, and assignment
4300 // operations and destructors can't have default arguments.
4301 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4302 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004303 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004304 } else if (MD->isVariadic()) {
4305 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4306 << CSM << MD->getSourceRange();
4307 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004308 }
4309
Richard Smith3003e1d2012-05-15 04:39:51 +00004310 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004311
Richard Smith7756afa2012-06-10 05:43:50 +00004312 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004313 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004314 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004315 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004316 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004317
Richard Smith3003e1d2012-05-15 04:39:51 +00004318 QualType ReturnType = Context.VoidTy;
4319 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4320 // Check for return type matching.
4321 ReturnType = Type->getResultType();
4322 QualType ExpectedReturnType =
4323 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4324 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4325 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4326 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4327 HadError = true;
4328 }
4329
4330 // A defaulted special member cannot have cv-qualifiers.
4331 if (Type->getTypeQuals()) {
4332 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4333 << (CSM == CXXMoveAssignment);
4334 HadError = true;
4335 }
4336 }
4337
4338 // Check for parameter type matching.
4339 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004340 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004341 if (ExpectedParams && ArgType->isReferenceType()) {
4342 // Argument must be reference to possibly-const T.
4343 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004344 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004345
4346 if (ReferentType.isVolatileQualified()) {
4347 Diag(MD->getLocation(),
4348 diag::err_defaulted_special_member_volatile_param) << CSM;
4349 HadError = true;
4350 }
4351
Richard Smith7756afa2012-06-10 05:43:50 +00004352 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004353 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4354 Diag(MD->getLocation(),
4355 diag::err_defaulted_special_member_copy_const_param)
4356 << (CSM == CXXCopyAssignment);
4357 // FIXME: Explain why this special member can't be const.
4358 } else {
4359 Diag(MD->getLocation(),
4360 diag::err_defaulted_special_member_move_const_param)
4361 << (CSM == CXXMoveAssignment);
4362 }
4363 HadError = true;
4364 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004365 } else if (ExpectedParams) {
4366 // A copy assignment operator can take its argument by value, but a
4367 // defaulted one cannot.
4368 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004369 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004370 HadError = true;
4371 }
Sean Huntbe631222011-05-17 20:44:43 +00004372
Richard Smith61802452011-12-22 02:22:31 +00004373 // C++11 [dcl.fct.def.default]p2:
4374 // An explicitly-defaulted function may be declared constexpr only if it
4375 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004376 // Do not apply this rule to members of class templates, since core issue 1358
4377 // makes such functions always instantiate to constexpr functions. For
4378 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004379 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4380 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004381 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4382 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4383 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004384 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004385 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004386 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004387
Richard Smith61802452011-12-22 02:22:31 +00004388 // and may have an explicit exception-specification only if it is compatible
4389 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004390 if (Type->hasExceptionSpec()) {
4391 // Delay the check if this is the first declaration of the special member,
4392 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004393 if (First) {
4394 // If the exception specification needs to be instantiated, do so now,
4395 // before we clobber it with an EST_Unevaluated specification below.
4396 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4397 InstantiateExceptionSpec(MD->getLocStart(), MD);
4398 Type = MD->getType()->getAs<FunctionProtoType>();
4399 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004400 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004401 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004402 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4403 }
Richard Smith61802452011-12-22 02:22:31 +00004404
4405 // If a function is explicitly defaulted on its first declaration,
4406 if (First) {
4407 // -- it is implicitly considered to be constexpr if the implicit
4408 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004409 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004410
Richard Smith3003e1d2012-05-15 04:39:51 +00004411 // -- it is implicitly considered to have the same exception-specification
4412 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004413 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4414 EPI.ExceptionSpecType = EST_Unevaluated;
4415 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004416 MD->setType(Context.getFunctionType(ReturnType,
4417 ArrayRef<QualType>(&ArgType,
4418 ExpectedParams),
4419 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004420 }
4421
Richard Smith3003e1d2012-05-15 04:39:51 +00004422 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004423 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004424 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004425 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004426 // C++11 [dcl.fct.def.default]p4:
4427 // [For a] user-provided explicitly-defaulted function [...] if such a
4428 // function is implicitly defined as deleted, the program is ill-formed.
4429 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4430 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004431 }
4432 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004433
Richard Smith3003e1d2012-05-15 04:39:51 +00004434 if (HadError)
4435 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004436}
4437
Richard Smith1d28caf2012-12-11 01:14:52 +00004438/// Check whether the exception specification provided for an
4439/// explicitly-defaulted special member matches the exception specification
4440/// that would have been generated for an implicit special member, per
4441/// C++11 [dcl.fct.def.default]p2.
4442void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4443 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4444 // Compute the implicit exception specification.
4445 FunctionProtoType::ExtProtoInfo EPI;
4446 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4447 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004448 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004449
4450 // Ensure that it matches.
4451 CheckEquivalentExceptionSpec(
4452 PDiag(diag::err_incorrect_defaulted_exception_spec)
4453 << getSpecialMember(MD), PDiag(),
4454 ImplicitType, SourceLocation(),
4455 SpecifiedType, MD->getLocation());
4456}
4457
4458void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4459 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4460 I != N; ++I)
4461 CheckExplicitlyDefaultedMemberExceptionSpec(
4462 DelayedDefaultedMemberExceptionSpecs[I].first,
4463 DelayedDefaultedMemberExceptionSpecs[I].second);
4464
4465 DelayedDefaultedMemberExceptionSpecs.clear();
4466}
4467
Richard Smith7d5088a2012-02-18 02:02:13 +00004468namespace {
4469struct SpecialMemberDeletionInfo {
4470 Sema &S;
4471 CXXMethodDecl *MD;
4472 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004473 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004474
4475 // Properties of the special member, computed for convenience.
4476 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4477 SourceLocation Loc;
4478
4479 bool AllFieldsAreConst;
4480
4481 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004482 Sema::CXXSpecialMember CSM, bool Diagnose)
4483 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004484 IsConstructor(false), IsAssignment(false), IsMove(false),
4485 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4486 AllFieldsAreConst(true) {
4487 switch (CSM) {
4488 case Sema::CXXDefaultConstructor:
4489 case Sema::CXXCopyConstructor:
4490 IsConstructor = true;
4491 break;
4492 case Sema::CXXMoveConstructor:
4493 IsConstructor = true;
4494 IsMove = true;
4495 break;
4496 case Sema::CXXCopyAssignment:
4497 IsAssignment = true;
4498 break;
4499 case Sema::CXXMoveAssignment:
4500 IsAssignment = true;
4501 IsMove = true;
4502 break;
4503 case Sema::CXXDestructor:
4504 break;
4505 case Sema::CXXInvalid:
4506 llvm_unreachable("invalid special member kind");
4507 }
4508
4509 if (MD->getNumParams()) {
4510 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4511 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4512 }
4513 }
4514
4515 bool inUnion() const { return MD->getParent()->isUnion(); }
4516
4517 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004518 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4519 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004520 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004521 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4522 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4523 Quals = 0;
4524 return S.LookupSpecialMember(Class, CSM,
4525 ConstArg || (Quals & Qualifiers::Const),
4526 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004527 MD->getRefQualifier() == RQ_RValue,
4528 TQ & Qualifiers::Const,
4529 TQ & Qualifiers::Volatile);
4530 }
4531
Richard Smith6c4c36c2012-03-30 20:53:28 +00004532 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004533
Richard Smith6c4c36c2012-03-30 20:53:28 +00004534 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004535 bool shouldDeleteForField(FieldDecl *FD);
4536 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004537
Richard Smith517bb842012-07-18 03:51:16 +00004538 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4539 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004540 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4541 Sema::SpecialMemberOverloadResult *SMOR,
4542 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004543
4544 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004545};
4546}
4547
John McCall12d8d802012-04-09 20:53:23 +00004548/// Is the given special member inaccessible when used on the given
4549/// sub-object.
4550bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4551 CXXMethodDecl *target) {
4552 /// If we're operating on a base class, the object type is the
4553 /// type of this special member.
4554 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004555 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004556 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4557 objectTy = S.Context.getTypeDeclType(MD->getParent());
4558 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4559
4560 // If we're operating on a field, the object type is the type of the field.
4561 } else {
4562 objectTy = S.Context.getTypeDeclType(target->getParent());
4563 }
4564
4565 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4566}
4567
Richard Smith6c4c36c2012-03-30 20:53:28 +00004568/// Check whether we should delete a special member due to the implicit
4569/// definition containing a call to a special member of a subobject.
4570bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4571 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4572 bool IsDtorCallInCtor) {
4573 CXXMethodDecl *Decl = SMOR->getMethod();
4574 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4575
4576 int DiagKind = -1;
4577
4578 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4579 DiagKind = !Decl ? 0 : 1;
4580 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4581 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004582 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004583 DiagKind = 3;
4584 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4585 !Decl->isTrivial()) {
4586 // A member of a union must have a trivial corresponding special member.
4587 // As a weird special case, a destructor call from a union's constructor
4588 // must be accessible and non-deleted, but need not be trivial. Such a
4589 // destructor is never actually called, but is semantically checked as
4590 // if it were.
4591 DiagKind = 4;
4592 }
4593
4594 if (DiagKind == -1)
4595 return false;
4596
4597 if (Diagnose) {
4598 if (Field) {
4599 S.Diag(Field->getLocation(),
4600 diag::note_deleted_special_member_class_subobject)
4601 << CSM << MD->getParent() << /*IsField*/true
4602 << Field << DiagKind << IsDtorCallInCtor;
4603 } else {
4604 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4605 S.Diag(Base->getLocStart(),
4606 diag::note_deleted_special_member_class_subobject)
4607 << CSM << MD->getParent() << /*IsField*/false
4608 << Base->getType() << DiagKind << IsDtorCallInCtor;
4609 }
4610
4611 if (DiagKind == 1)
4612 S.NoteDeletedFunction(Decl);
4613 // FIXME: Explain inaccessibility if DiagKind == 3.
4614 }
4615
4616 return true;
4617}
4618
Richard Smith9a561d52012-02-26 09:11:52 +00004619/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004620/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004621bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004622 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004623 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004624
4625 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004626 // -- any direct or virtual base class, or non-static data member with no
4627 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004628 // either M has no default constructor or overload resolution as applied
4629 // to M's default constructor results in an ambiguity or in a function
4630 // that is deleted or inaccessible
4631 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4632 // -- a direct or virtual base class B that cannot be copied/moved because
4633 // overload resolution, as applied to B's corresponding special member,
4634 // results in an ambiguity or a function that is deleted or inaccessible
4635 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004636 // C++11 [class.dtor]p5:
4637 // -- any direct or virtual base class [...] has a type with a destructor
4638 // that is deleted or inaccessible
4639 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004640 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004641 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004642 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004643
Richard Smith6c4c36c2012-03-30 20:53:28 +00004644 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4645 // -- any direct or virtual base class or non-static data member has a
4646 // type with a destructor that is deleted or inaccessible
4647 if (IsConstructor) {
4648 Sema::SpecialMemberOverloadResult *SMOR =
4649 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4650 false, false, false, false, false);
4651 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4652 return true;
4653 }
4654
Richard Smith9a561d52012-02-26 09:11:52 +00004655 return false;
4656}
4657
4658/// Check whether we should delete a special member function due to the class
4659/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004660bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004661 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004662 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004663}
4664
4665/// Check whether we should delete a special member function due to the class
4666/// having a particular non-static data member.
4667bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4668 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4669 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4670
4671 if (CSM == Sema::CXXDefaultConstructor) {
4672 // For a default constructor, all references must be initialized in-class
4673 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004674 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4675 if (Diagnose)
4676 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4677 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004678 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004679 }
Richard Smith79363f52012-02-27 06:07:25 +00004680 // C++11 [class.ctor]p5: any non-variant non-static data member of
4681 // const-qualified type (or array thereof) with no
4682 // brace-or-equal-initializer does not have a user-provided default
4683 // constructor.
4684 if (!inUnion() && FieldType.isConstQualified() &&
4685 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004686 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4687 if (Diagnose)
4688 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004689 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004690 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004691 }
4692
4693 if (inUnion() && !FieldType.isConstQualified())
4694 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004695 } else if (CSM == Sema::CXXCopyConstructor) {
4696 // For a copy constructor, data members must not be of rvalue reference
4697 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004698 if (FieldType->isRValueReferenceType()) {
4699 if (Diagnose)
4700 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4701 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004702 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004703 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004704 } else if (IsAssignment) {
4705 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004706 if (FieldType->isReferenceType()) {
4707 if (Diagnose)
4708 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4709 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004710 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004711 }
4712 if (!FieldRecord && FieldType.isConstQualified()) {
4713 // C++11 [class.copy]p23:
4714 // -- a non-static data member of const non-class type (or array thereof)
4715 if (Diagnose)
4716 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004717 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004718 return true;
4719 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004720 }
4721
4722 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004723 // Some additional restrictions exist on the variant members.
4724 if (!inUnion() && FieldRecord->isUnion() &&
4725 FieldRecord->isAnonymousStructOrUnion()) {
4726 bool AllVariantFieldsAreConst = true;
4727
Richard Smithdf8dc862012-03-29 19:00:10 +00004728 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004729 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4730 UE = FieldRecord->field_end();
4731 UI != UE; ++UI) {
4732 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004733
4734 if (!UnionFieldType.isConstQualified())
4735 AllVariantFieldsAreConst = false;
4736
Richard Smith9a561d52012-02-26 09:11:52 +00004737 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4738 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004739 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4740 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004741 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004742 }
4743
4744 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004745 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004746 FieldRecord->field_begin() != FieldRecord->field_end()) {
4747 if (Diagnose)
4748 S.Diag(FieldRecord->getLocation(),
4749 diag::note_deleted_default_ctor_all_const)
4750 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004751 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004752 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004753
Richard Smithdf8dc862012-03-29 19:00:10 +00004754 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004755 // This is technically non-conformant, but sanity demands it.
4756 return false;
4757 }
4758
Richard Smith517bb842012-07-18 03:51:16 +00004759 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4760 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004761 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004762 }
4763
4764 return false;
4765}
4766
4767/// C++11 [class.ctor] p5:
4768/// A defaulted default constructor for a class X is defined as deleted if
4769/// X is a union and all of its variant members are of const-qualified type.
4770bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004771 // This is a silly definition, because it gives an empty union a deleted
4772 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004773 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4774 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4775 if (Diagnose)
4776 S.Diag(MD->getParent()->getLocation(),
4777 diag::note_deleted_default_ctor_all_const)
4778 << MD->getParent() << /*not anonymous union*/0;
4779 return true;
4780 }
4781 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004782}
4783
4784/// Determine whether a defaulted special member function should be defined as
4785/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4786/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004787bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4788 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004789 if (MD->isInvalidDecl())
4790 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004791 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004792 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004793 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004794 return false;
4795
Richard Smith7d5088a2012-02-18 02:02:13 +00004796 // C++11 [expr.lambda.prim]p19:
4797 // The closure type associated with a lambda-expression has a
4798 // deleted (8.4.3) default constructor and a deleted copy
4799 // assignment operator.
4800 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004801 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4802 if (Diagnose)
4803 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004804 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004805 }
4806
Richard Smith5bdaac52012-04-02 20:59:25 +00004807 // For an anonymous struct or union, the copy and assignment special members
4808 // will never be used, so skip the check. For an anonymous union declared at
4809 // namespace scope, the constructor and destructor are used.
4810 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4811 RD->isAnonymousStructOrUnion())
4812 return false;
4813
Richard Smith6c4c36c2012-03-30 20:53:28 +00004814 // C++11 [class.copy]p7, p18:
4815 // If the class definition declares a move constructor or move assignment
4816 // operator, an implicitly declared copy constructor or copy assignment
4817 // operator is defined as deleted.
4818 if (MD->isImplicit() &&
4819 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4820 CXXMethodDecl *UserDeclaredMove = 0;
4821
4822 // In Microsoft mode, a user-declared move only causes the deletion of the
4823 // corresponding copy operation, not both copy operations.
4824 if (RD->hasUserDeclaredMoveConstructor() &&
4825 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4826 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004827
4828 // Find any user-declared move constructor.
4829 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4830 E = RD->ctor_end(); I != E; ++I) {
4831 if (I->isMoveConstructor()) {
4832 UserDeclaredMove = *I;
4833 break;
4834 }
4835 }
Richard Smith1c931be2012-04-02 18:40:40 +00004836 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004837 } else if (RD->hasUserDeclaredMoveAssignment() &&
4838 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4839 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004840
4841 // Find any user-declared move assignment operator.
4842 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4843 E = RD->method_end(); I != E; ++I) {
4844 if (I->isMoveAssignmentOperator()) {
4845 UserDeclaredMove = *I;
4846 break;
4847 }
4848 }
Richard Smith1c931be2012-04-02 18:40:40 +00004849 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004850 }
4851
4852 if (UserDeclaredMove) {
4853 Diag(UserDeclaredMove->getLocation(),
4854 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004855 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004856 << UserDeclaredMove->isMoveAssignmentOperator();
4857 return true;
4858 }
4859 }
Sean Hunte16da072011-10-10 06:18:57 +00004860
Richard Smith5bdaac52012-04-02 20:59:25 +00004861 // Do access control from the special member function
4862 ContextRAII MethodContext(*this, MD);
4863
Richard Smith9a561d52012-02-26 09:11:52 +00004864 // C++11 [class.dtor]p5:
4865 // -- for a virtual destructor, lookup of the non-array deallocation function
4866 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004867 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004868 FunctionDecl *OperatorDelete = 0;
4869 DeclarationName Name =
4870 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4871 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004872 OperatorDelete, false)) {
4873 if (Diagnose)
4874 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004875 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004876 }
Richard Smith9a561d52012-02-26 09:11:52 +00004877 }
4878
Richard Smith6c4c36c2012-03-30 20:53:28 +00004879 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004880
Sean Huntcdee3fe2011-05-11 22:34:38 +00004881 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004882 BE = RD->bases_end(); BI != BE; ++BI)
4883 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004884 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004885 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004886
4887 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004888 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004889 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004890 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004891
4892 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004893 FE = RD->field_end(); FI != FE; ++FI)
4894 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004895 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004896 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004897
Richard Smith7d5088a2012-02-18 02:02:13 +00004898 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004899 return true;
4900
4901 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004902}
4903
Richard Smithac713512012-12-08 02:53:02 +00004904/// Perform lookup for a special member of the specified kind, and determine
4905/// whether it is trivial. If the triviality can be determined without the
4906/// lookup, skip it. This is intended for use when determining whether a
4907/// special member of a containing object is trivial, and thus does not ever
4908/// perform overload resolution for default constructors.
4909///
4910/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4911/// member that was most likely to be intended to be trivial, if any.
4912static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4913 Sema::CXXSpecialMember CSM, unsigned Quals,
4914 CXXMethodDecl **Selected) {
4915 if (Selected)
4916 *Selected = 0;
4917
4918 switch (CSM) {
4919 case Sema::CXXInvalid:
4920 llvm_unreachable("not a special member");
4921
4922 case Sema::CXXDefaultConstructor:
4923 // C++11 [class.ctor]p5:
4924 // A default constructor is trivial if:
4925 // - all the [direct subobjects] have trivial default constructors
4926 //
4927 // Note, no overload resolution is performed in this case.
4928 if (RD->hasTrivialDefaultConstructor())
4929 return true;
4930
4931 if (Selected) {
4932 // If there's a default constructor which could have been trivial, dig it
4933 // out. Otherwise, if there's any user-provided default constructor, point
4934 // to that as an example of why there's not a trivial one.
4935 CXXConstructorDecl *DefCtor = 0;
4936 if (RD->needsImplicitDefaultConstructor())
4937 S.DeclareImplicitDefaultConstructor(RD);
4938 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4939 CE = RD->ctor_end(); CI != CE; ++CI) {
4940 if (!CI->isDefaultConstructor())
4941 continue;
4942 DefCtor = *CI;
4943 if (!DefCtor->isUserProvided())
4944 break;
4945 }
4946
4947 *Selected = DefCtor;
4948 }
4949
4950 return false;
4951
4952 case Sema::CXXDestructor:
4953 // C++11 [class.dtor]p5:
4954 // A destructor is trivial if:
4955 // - all the direct [subobjects] have trivial destructors
4956 if (RD->hasTrivialDestructor())
4957 return true;
4958
4959 if (Selected) {
4960 if (RD->needsImplicitDestructor())
4961 S.DeclareImplicitDestructor(RD);
4962 *Selected = RD->getDestructor();
4963 }
4964
4965 return false;
4966
4967 case Sema::CXXCopyConstructor:
4968 // C++11 [class.copy]p12:
4969 // A copy constructor is trivial if:
4970 // - the constructor selected to copy each direct [subobject] is trivial
4971 if (RD->hasTrivialCopyConstructor()) {
4972 if (Quals == Qualifiers::Const)
4973 // We must either select the trivial copy constructor or reach an
4974 // ambiguity; no need to actually perform overload resolution.
4975 return true;
4976 } else if (!Selected) {
4977 return false;
4978 }
4979 // In C++98, we are not supposed to perform overload resolution here, but we
4980 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4981 // cases like B as having a non-trivial copy constructor:
4982 // struct A { template<typename T> A(T&); };
4983 // struct B { mutable A a; };
4984 goto NeedOverloadResolution;
4985
4986 case Sema::CXXCopyAssignment:
4987 // C++11 [class.copy]p25:
4988 // A copy assignment operator is trivial if:
4989 // - the assignment operator selected to copy each direct [subobject] is
4990 // trivial
4991 if (RD->hasTrivialCopyAssignment()) {
4992 if (Quals == Qualifiers::Const)
4993 return true;
4994 } else if (!Selected) {
4995 return false;
4996 }
4997 // In C++98, we are not supposed to perform overload resolution here, but we
4998 // treat that as a language defect.
4999 goto NeedOverloadResolution;
5000
5001 case Sema::CXXMoveConstructor:
5002 case Sema::CXXMoveAssignment:
5003 NeedOverloadResolution:
5004 Sema::SpecialMemberOverloadResult *SMOR =
5005 S.LookupSpecialMember(RD, CSM,
5006 Quals & Qualifiers::Const,
5007 Quals & Qualifiers::Volatile,
5008 /*RValueThis*/false, /*ConstThis*/false,
5009 /*VolatileThis*/false);
5010
5011 // The standard doesn't describe how to behave if the lookup is ambiguous.
5012 // We treat it as not making the member non-trivial, just like the standard
5013 // mandates for the default constructor. This should rarely matter, because
5014 // the member will also be deleted.
5015 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5016 return true;
5017
5018 if (!SMOR->getMethod()) {
5019 assert(SMOR->getKind() ==
5020 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5021 return false;
5022 }
5023
5024 // We deliberately don't check if we found a deleted special member. We're
5025 // not supposed to!
5026 if (Selected)
5027 *Selected = SMOR->getMethod();
5028 return SMOR->getMethod()->isTrivial();
5029 }
5030
5031 llvm_unreachable("unknown special method kind");
5032}
5033
Benjamin Kramera574c892013-02-15 12:30:38 +00005034static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005035 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5036 CI != CE; ++CI)
5037 if (!CI->isImplicit())
5038 return *CI;
5039
5040 // Look for constructor templates.
5041 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5042 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5043 if (CXXConstructorDecl *CD =
5044 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5045 return CD;
5046 }
5047
5048 return 0;
5049}
5050
5051/// The kind of subobject we are checking for triviality. The values of this
5052/// enumeration are used in diagnostics.
5053enum TrivialSubobjectKind {
5054 /// The subobject is a base class.
5055 TSK_BaseClass,
5056 /// The subobject is a non-static data member.
5057 TSK_Field,
5058 /// The object is actually the complete object.
5059 TSK_CompleteObject
5060};
5061
5062/// Check whether the special member selected for a given type would be trivial.
5063static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5064 QualType SubType,
5065 Sema::CXXSpecialMember CSM,
5066 TrivialSubobjectKind Kind,
5067 bool Diagnose) {
5068 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5069 if (!SubRD)
5070 return true;
5071
5072 CXXMethodDecl *Selected;
5073 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5074 Diagnose ? &Selected : 0))
5075 return true;
5076
5077 if (Diagnose) {
5078 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5079 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5080 << Kind << SubType.getUnqualifiedType();
5081 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5082 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5083 } else if (!Selected)
5084 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5085 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5086 else if (Selected->isUserProvided()) {
5087 if (Kind == TSK_CompleteObject)
5088 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5089 << Kind << SubType.getUnqualifiedType() << CSM;
5090 else {
5091 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5092 << Kind << SubType.getUnqualifiedType() << CSM;
5093 S.Diag(Selected->getLocation(), diag::note_declared_at);
5094 }
5095 } else {
5096 if (Kind != TSK_CompleteObject)
5097 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5098 << Kind << SubType.getUnqualifiedType() << CSM;
5099
5100 // Explain why the defaulted or deleted special member isn't trivial.
5101 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5102 }
5103 }
5104
5105 return false;
5106}
5107
5108/// Check whether the members of a class type allow a special member to be
5109/// trivial.
5110static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5111 Sema::CXXSpecialMember CSM,
5112 bool ConstArg, bool Diagnose) {
5113 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5114 FE = RD->field_end(); FI != FE; ++FI) {
5115 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5116 continue;
5117
5118 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5119
5120 // Pretend anonymous struct or union members are members of this class.
5121 if (FI->isAnonymousStructOrUnion()) {
5122 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5123 CSM, ConstArg, Diagnose))
5124 return false;
5125 continue;
5126 }
5127
5128 // C++11 [class.ctor]p5:
5129 // A default constructor is trivial if [...]
5130 // -- no non-static data member of its class has a
5131 // brace-or-equal-initializer
5132 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5133 if (Diagnose)
5134 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5135 return false;
5136 }
5137
5138 // Objective C ARC 4.3.5:
5139 // [...] nontrivally ownership-qualified types are [...] not trivially
5140 // default constructible, copy constructible, move constructible, copy
5141 // assignable, move assignable, or destructible [...]
5142 if (S.getLangOpts().ObjCAutoRefCount &&
5143 FieldType.hasNonTrivialObjCLifetime()) {
5144 if (Diagnose)
5145 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5146 << RD << FieldType.getObjCLifetime();
5147 return false;
5148 }
5149
5150 if (ConstArg && !FI->isMutable())
5151 FieldType.addConst();
5152 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5153 TSK_Field, Diagnose))
5154 return false;
5155 }
5156
5157 return true;
5158}
5159
5160/// Diagnose why the specified class does not have a trivial special member of
5161/// the given kind.
5162void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5163 QualType Ty = Context.getRecordType(RD);
5164 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5165 Ty.addConst();
5166
5167 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5168 TSK_CompleteObject, /*Diagnose*/true);
5169}
5170
5171/// Determine whether a defaulted or deleted special member function is trivial,
5172/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5173/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5174bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5175 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005176 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5177
5178 CXXRecordDecl *RD = MD->getParent();
5179
5180 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005181
5182 // C++11 [class.copy]p12, p25:
5183 // A [special member] is trivial if its declared parameter type is the same
5184 // as if it had been implicitly declared [...]
5185 switch (CSM) {
5186 case CXXDefaultConstructor:
5187 case CXXDestructor:
5188 // Trivial default constructors and destructors cannot have parameters.
5189 break;
5190
5191 case CXXCopyConstructor:
5192 case CXXCopyAssignment: {
5193 // Trivial copy operations always have const, non-volatile parameter types.
5194 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005195 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005196 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5197 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5198 if (Diagnose)
5199 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5200 << Param0->getSourceRange() << Param0->getType()
5201 << Context.getLValueReferenceType(
5202 Context.getRecordType(RD).withConst());
5203 return false;
5204 }
5205 break;
5206 }
5207
5208 case CXXMoveConstructor:
5209 case CXXMoveAssignment: {
5210 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005211 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005212 const RValueReferenceType *RT =
5213 Param0->getType()->getAs<RValueReferenceType>();
5214 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5215 if (Diagnose)
5216 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5217 << Param0->getSourceRange() << Param0->getType()
5218 << Context.getRValueReferenceType(Context.getRecordType(RD));
5219 return false;
5220 }
5221 break;
5222 }
5223
5224 case CXXInvalid:
5225 llvm_unreachable("not a special member");
5226 }
5227
5228 // FIXME: We require that the parameter-declaration-clause is equivalent to
5229 // that of an implicit declaration, not just that the declared parameter type
5230 // matches, in order to prevent absuridities like a function simultaneously
5231 // being a trivial copy constructor and a non-trivial default constructor.
5232 // This issue has not yet been assigned a core issue number.
5233 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5234 if (Diagnose)
5235 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5236 diag::note_nontrivial_default_arg)
5237 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5238 return false;
5239 }
5240 if (MD->isVariadic()) {
5241 if (Diagnose)
5242 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5243 return false;
5244 }
5245
5246 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5247 // A copy/move [constructor or assignment operator] is trivial if
5248 // -- the [member] selected to copy/move each direct base class subobject
5249 // is trivial
5250 //
5251 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5252 // A [default constructor or destructor] is trivial if
5253 // -- all the direct base classes have trivial [default constructors or
5254 // destructors]
5255 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5256 BE = RD->bases_end(); BI != BE; ++BI)
5257 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5258 ConstArg ? BI->getType().withConst()
5259 : BI->getType(),
5260 CSM, TSK_BaseClass, Diagnose))
5261 return false;
5262
5263 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5264 // A copy/move [constructor or assignment operator] for a class X is
5265 // trivial if
5266 // -- for each non-static data member of X that is of class type (or array
5267 // thereof), the constructor selected to copy/move that member is
5268 // trivial
5269 //
5270 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5271 // A [default constructor or destructor] is trivial if
5272 // -- for all of the non-static data members of its class that are of class
5273 // type (or array thereof), each such class has a trivial [default
5274 // constructor or destructor]
5275 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5276 return false;
5277
5278 // C++11 [class.dtor]p5:
5279 // A destructor is trivial if [...]
5280 // -- the destructor is not virtual
5281 if (CSM == CXXDestructor && MD->isVirtual()) {
5282 if (Diagnose)
5283 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5284 return false;
5285 }
5286
5287 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5288 // A [special member] for class X is trivial if [...]
5289 // -- class X has no virtual functions and no virtual base classes
5290 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5291 if (!Diagnose)
5292 return false;
5293
5294 if (RD->getNumVBases()) {
5295 // Check for virtual bases. We already know that the corresponding
5296 // member in all bases is trivial, so vbases must all be direct.
5297 CXXBaseSpecifier &BS = *RD->vbases_begin();
5298 assert(BS.isVirtual());
5299 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5300 return false;
5301 }
5302
5303 // Must have a virtual method.
5304 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5305 ME = RD->method_end(); MI != ME; ++MI) {
5306 if (MI->isVirtual()) {
5307 SourceLocation MLoc = MI->getLocStart();
5308 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5309 return false;
5310 }
5311 }
5312
5313 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5314 }
5315
5316 // Looks like it's trivial!
5317 return true;
5318}
5319
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005320/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005321namespace {
5322 struct FindHiddenVirtualMethodData {
5323 Sema *S;
5324 CXXMethodDecl *Method;
5325 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005326 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005327 };
5328}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005329
David Blaikie5f750682012-10-19 00:53:08 +00005330/// \brief Check whether any most overriden method from MD in Methods
5331static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5332 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5333 if (MD->size_overridden_methods() == 0)
5334 return Methods.count(MD->getCanonicalDecl());
5335 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5336 E = MD->end_overridden_methods();
5337 I != E; ++I)
5338 if (CheckMostOverridenMethods(*I, Methods))
5339 return true;
5340 return false;
5341}
5342
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005343/// \brief Member lookup function that determines whether a given C++
5344/// method overloads virtual methods in a base class without overriding any,
5345/// to be used with CXXRecordDecl::lookupInBases().
5346static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5347 CXXBasePath &Path,
5348 void *UserData) {
5349 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5350
5351 FindHiddenVirtualMethodData &Data
5352 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5353
5354 DeclarationName Name = Data.Method->getDeclName();
5355 assert(Name.getNameKind() == DeclarationName::Identifier);
5356
5357 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005358 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005359 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005360 !Path.Decls.empty();
5361 Path.Decls = Path.Decls.slice(1)) {
5362 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005364 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005365 foundSameNameMethod = true;
5366 // Interested only in hidden virtual methods.
5367 if (!MD->isVirtual())
5368 continue;
5369 // If the method we are checking overrides a method from its base
5370 // don't warn about the other overloaded methods.
5371 if (!Data.S->IsOverload(Data.Method, MD, false))
5372 return true;
5373 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005374 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005375 overloadedMethods.push_back(MD);
5376 }
5377 }
5378
5379 if (foundSameNameMethod)
5380 Data.OverloadedMethods.append(overloadedMethods.begin(),
5381 overloadedMethods.end());
5382 return foundSameNameMethod;
5383}
5384
David Blaikie5f750682012-10-19 00:53:08 +00005385/// \brief Add the most overriden methods from MD to Methods
5386static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5387 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5388 if (MD->size_overridden_methods() == 0)
5389 Methods.insert(MD->getCanonicalDecl());
5390 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5391 E = MD->end_overridden_methods();
5392 I != E; ++I)
5393 AddMostOverridenMethods(*I, Methods);
5394}
5395
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005396/// \brief See if a method overloads virtual methods in a base class without
5397/// overriding any.
5398void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5399 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005400 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005401 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005402 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005403 return;
5404
5405 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5406 /*bool RecordPaths=*/false,
5407 /*bool DetectVirtual=*/false);
5408 FindHiddenVirtualMethodData Data;
5409 Data.Method = MD;
5410 Data.S = this;
5411
5412 // Keep the base methods that were overriden or introduced in the subclass
5413 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005414 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5415 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5416 NamedDecl *ND = *I;
5417 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005418 ND = shad->getTargetDecl();
5419 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5420 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005421 }
5422
5423 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5424 !Data.OverloadedMethods.empty()) {
5425 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5426 << MD << (Data.OverloadedMethods.size() > 1);
5427
5428 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5429 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005430 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005431 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005432 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5433 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005434 }
5435 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005436}
5437
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005438void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005439 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005440 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005441 SourceLocation RBrac,
5442 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005443 if (!TagDecl)
5444 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005445
Douglas Gregor42af25f2009-05-11 19:58:34 +00005446 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005447
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005448 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5449 if (l->getKind() != AttributeList::AT_Visibility)
5450 continue;
5451 l->setInvalid();
5452 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5453 l->getName();
5454 }
5455
David Blaikie77b6de02011-09-22 02:58:26 +00005456 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005457 // strict aliasing violation!
5458 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005459 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005460
Douglas Gregor23c94db2010-07-02 17:43:08 +00005461 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005462 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005463}
5464
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005465/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5466/// special functions, such as the default constructor, copy
5467/// constructor, or destructor, to the given C++ class (C++
5468/// [special]p1). This routine can only be executed just before the
5469/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005470void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005471 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005472 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005473
Richard Smithbc2a35d2012-12-08 08:32:28 +00005474 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005475 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005476
Richard Smithbc2a35d2012-12-08 08:32:28 +00005477 // If the properties or semantics of the copy constructor couldn't be
5478 // determined while the class was being declared, force a declaration
5479 // of it now.
5480 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5481 DeclareImplicitCopyConstructor(ClassDecl);
5482 }
5483
Richard Smith80ad52f2013-01-02 11:42:31 +00005484 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005485 ++ASTContext::NumImplicitMoveConstructors;
5486
Richard Smithbc2a35d2012-12-08 08:32:28 +00005487 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5488 DeclareImplicitMoveConstructor(ClassDecl);
5489 }
5490
Douglas Gregora376d102010-07-02 21:50:04 +00005491 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5492 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005493
5494 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005495 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005496 // it shows up in the right place in the vtable and that we diagnose
5497 // problems with the implicit exception specification.
5498 if (ClassDecl->isDynamicClass() ||
5499 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005500 DeclareImplicitCopyAssignment(ClassDecl);
5501 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005502
Richard Smith80ad52f2013-01-02 11:42:31 +00005503 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005504 ++ASTContext::NumImplicitMoveAssignmentOperators;
5505
5506 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005507 if (ClassDecl->isDynamicClass() ||
5508 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005509 DeclareImplicitMoveAssignment(ClassDecl);
5510 }
5511
Douglas Gregor4923aa22010-07-02 20:37:36 +00005512 if (!ClassDecl->hasUserDeclaredDestructor()) {
5513 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005514
5515 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005516 // have to declare the destructor immediately. This ensures that, e.g., it
5517 // shows up in the right place in the vtable and that we diagnose problems
5518 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005519 if (ClassDecl->isDynamicClass() ||
5520 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005521 DeclareImplicitDestructor(ClassDecl);
5522 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005523}
5524
Francois Pichet8387e2a2011-04-22 22:18:13 +00005525void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5526 if (!D)
5527 return;
5528
5529 int NumParamList = D->getNumTemplateParameterLists();
5530 for (int i = 0; i < NumParamList; i++) {
5531 TemplateParameterList* Params = D->getTemplateParameterList(i);
5532 for (TemplateParameterList::iterator Param = Params->begin(),
5533 ParamEnd = Params->end();
5534 Param != ParamEnd; ++Param) {
5535 NamedDecl *Named = cast<NamedDecl>(*Param);
5536 if (Named->getDeclName()) {
5537 S->AddDecl(Named);
5538 IdResolver.AddDecl(Named);
5539 }
5540 }
5541 }
5542}
5543
John McCalld226f652010-08-21 09:40:31 +00005544void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005545 if (!D)
5546 return;
5547
5548 TemplateParameterList *Params = 0;
5549 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5550 Params = Template->getTemplateParameters();
5551 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5552 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5553 Params = PartialSpec->getTemplateParameters();
5554 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005555 return;
5556
Douglas Gregor6569d682009-05-27 23:11:45 +00005557 for (TemplateParameterList::iterator Param = Params->begin(),
5558 ParamEnd = Params->end();
5559 Param != ParamEnd; ++Param) {
5560 NamedDecl *Named = cast<NamedDecl>(*Param);
5561 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005562 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005563 IdResolver.AddDecl(Named);
5564 }
5565 }
5566}
5567
John McCalld226f652010-08-21 09:40:31 +00005568void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005569 if (!RecordD) return;
5570 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005571 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005572 PushDeclContext(S, Record);
5573}
5574
John McCalld226f652010-08-21 09:40:31 +00005575void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005576 if (!RecordD) return;
5577 PopDeclContext();
5578}
5579
Douglas Gregor72b505b2008-12-16 21:30:33 +00005580/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5581/// parsing a top-level (non-nested) C++ class, and we are now
5582/// parsing those parts of the given Method declaration that could
5583/// not be parsed earlier (C++ [class.mem]p2), such as default
5584/// arguments. This action should enter the scope of the given
5585/// Method declaration as if we had just parsed the qualified method
5586/// name. However, it should not bring the parameters into scope;
5587/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005588void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005589}
5590
5591/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5592/// C++ method declaration. We're (re-)introducing the given
5593/// function parameter into scope for use in parsing later parts of
5594/// the method declaration. For example, we could see an
5595/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005596void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005597 if (!ParamD)
5598 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005599
John McCalld226f652010-08-21 09:40:31 +00005600 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005601
5602 // If this parameter has an unparsed default argument, clear it out
5603 // to make way for the parsed default argument.
5604 if (Param->hasUnparsedDefaultArg())
5605 Param->setDefaultArg(0);
5606
John McCalld226f652010-08-21 09:40:31 +00005607 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005608 if (Param->getDeclName())
5609 IdResolver.AddDecl(Param);
5610}
5611
5612/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5613/// processing the delayed method declaration for Method. The method
5614/// declaration is now considered finished. There may be a separate
5615/// ActOnStartOfFunctionDef action later (not necessarily
5616/// immediately!) for this method, if it was also defined inside the
5617/// class body.
John McCalld226f652010-08-21 09:40:31 +00005618void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005619 if (!MethodD)
5620 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005621
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005622 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005623
John McCalld226f652010-08-21 09:40:31 +00005624 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005625
5626 // Now that we have our default arguments, check the constructor
5627 // again. It could produce additional diagnostics or affect whether
5628 // the class has implicitly-declared destructors, among other
5629 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005630 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5631 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005632
5633 // Check the default arguments, which we may have added.
5634 if (!Method->isInvalidDecl())
5635 CheckCXXDefaultArguments(Method);
5636}
5637
Douglas Gregor42a552f2008-11-05 20:51:48 +00005638/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005639/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005640/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005641/// emit diagnostics and set the invalid bit to true. In any case, the type
5642/// will be updated to reflect a well-formed type for the constructor and
5643/// returned.
5644QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005645 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005646 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005647
5648 // C++ [class.ctor]p3:
5649 // A constructor shall not be virtual (10.3) or static (9.4). A
5650 // constructor can be invoked for a const, volatile or const
5651 // volatile object. A constructor shall not be declared const,
5652 // volatile, or const volatile (9.3.2).
5653 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005654 if (!D.isInvalidType())
5655 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5656 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5657 << SourceRange(D.getIdentifierLoc());
5658 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005659 }
John McCalld931b082010-08-26 03:08:43 +00005660 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005661 if (!D.isInvalidType())
5662 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5663 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5664 << SourceRange(D.getIdentifierLoc());
5665 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005666 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005667 }
Mike Stump1eb44332009-09-09 15:08:12 +00005668
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005669 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005670 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005671 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005672 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5673 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005674 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005675 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5676 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005677 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005678 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5679 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005680 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005681 }
Mike Stump1eb44332009-09-09 15:08:12 +00005682
Douglas Gregorc938c162011-01-26 05:01:58 +00005683 // C++0x [class.ctor]p4:
5684 // A constructor shall not be declared with a ref-qualifier.
5685 if (FTI.hasRefQualifier()) {
5686 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5687 << FTI.RefQualifierIsLValueRef
5688 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5689 D.setInvalidType();
5690 }
5691
Douglas Gregor42a552f2008-11-05 20:51:48 +00005692 // Rebuild the function type "R" without any type qualifiers (in
5693 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005694 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005695 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005696 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5697 return R;
5698
5699 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5700 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005701 EPI.RefQualifier = RQ_None;
5702
Richard Smith07b0fdc2013-03-18 21:12:30 +00005703 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005704}
5705
Douglas Gregor72b505b2008-12-16 21:30:33 +00005706/// CheckConstructor - Checks a fully-formed constructor for
5707/// well-formedness, issuing any diagnostics required. Returns true if
5708/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005709void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005710 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005711 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5712 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005713 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005714
5715 // C++ [class.copy]p3:
5716 // A declaration of a constructor for a class X is ill-formed if
5717 // its first parameter is of type (optionally cv-qualified) X and
5718 // either there are no other parameters or else all other
5719 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005720 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005721 ((Constructor->getNumParams() == 1) ||
5722 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005723 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5724 Constructor->getTemplateSpecializationKind()
5725 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005726 QualType ParamType = Constructor->getParamDecl(0)->getType();
5727 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5728 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005729 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005730 const char *ConstRef
5731 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5732 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005733 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005734 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005735
5736 // FIXME: Rather that making the constructor invalid, we should endeavor
5737 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005738 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005739 }
5740 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005741}
5742
John McCall15442822010-08-04 01:04:25 +00005743/// CheckDestructor - Checks a fully-formed destructor definition for
5744/// well-formedness, issuing any diagnostics required. Returns true
5745/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005746bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005747 CXXRecordDecl *RD = Destructor->getParent();
5748
5749 if (Destructor->isVirtual()) {
5750 SourceLocation Loc;
5751
5752 if (!Destructor->isImplicit())
5753 Loc = Destructor->getLocation();
5754 else
5755 Loc = RD->getLocation();
5756
5757 // If we have a virtual destructor, look up the deallocation function
5758 FunctionDecl *OperatorDelete = 0;
5759 DeclarationName Name =
5760 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005761 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005762 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005763
Eli Friedman5f2987c2012-02-02 03:46:19 +00005764 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005765
5766 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005767 }
Anders Carlsson37909802009-11-30 21:24:50 +00005768
5769 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005770}
5771
Mike Stump1eb44332009-09-09 15:08:12 +00005772static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005773FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5774 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5775 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005776 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005777}
5778
Douglas Gregor42a552f2008-11-05 20:51:48 +00005779/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5780/// the well-formednes of the destructor declarator @p D with type @p
5781/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005782/// emit diagnostics and set the declarator to invalid. Even if this happens,
5783/// will be updated to reflect a well-formed type for the destructor and
5784/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005785QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005786 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005787 // C++ [class.dtor]p1:
5788 // [...] A typedef-name that names a class is a class-name
5789 // (7.1.3); however, a typedef-name that names a class shall not
5790 // be used as the identifier in the declarator for a destructor
5791 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005792 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005793 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005794 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005795 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005796 else if (const TemplateSpecializationType *TST =
5797 DeclaratorType->getAs<TemplateSpecializationType>())
5798 if (TST->isTypeAlias())
5799 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5800 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005801
5802 // C++ [class.dtor]p2:
5803 // A destructor is used to destroy objects of its class type. A
5804 // destructor takes no parameters, and no return type can be
5805 // specified for it (not even void). The address of a destructor
5806 // shall not be taken. A destructor shall not be static. A
5807 // destructor can be invoked for a const, volatile or const
5808 // volatile object. A destructor shall not be declared const,
5809 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005810 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005811 if (!D.isInvalidType())
5812 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005814 << SourceRange(D.getIdentifierLoc())
5815 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5816
John McCalld931b082010-08-26 03:08:43 +00005817 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005818 }
Chris Lattner65401802009-04-25 08:28:21 +00005819 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005820 // Destructors don't have return types, but the parser will
5821 // happily parse something like:
5822 //
5823 // class X {
5824 // float ~X();
5825 // };
5826 //
5827 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005828 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5829 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5830 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005831 }
Mike Stump1eb44332009-09-09 15:08:12 +00005832
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005833 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005834 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005835 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005836 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5837 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005838 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005839 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5840 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005841 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005842 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5843 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005844 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005845 }
5846
Douglas Gregorc938c162011-01-26 05:01:58 +00005847 // C++0x [class.dtor]p2:
5848 // A destructor shall not be declared with a ref-qualifier.
5849 if (FTI.hasRefQualifier()) {
5850 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5851 << FTI.RefQualifierIsLValueRef
5852 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5853 D.setInvalidType();
5854 }
5855
Douglas Gregor42a552f2008-11-05 20:51:48 +00005856 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005857 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005858 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5859
5860 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005861 FTI.freeArgs();
5862 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005863 }
5864
Mike Stump1eb44332009-09-09 15:08:12 +00005865 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005866 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005867 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005868 D.setInvalidType();
5869 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005870
5871 // Rebuild the function type "R" without any type qualifiers or
5872 // parameters (in case any of the errors above fired) and with
5873 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005874 // types.
John McCalle23cf432010-12-14 08:05:40 +00005875 if (!D.isInvalidType())
5876 return R;
5877
Douglas Gregord92ec472010-07-01 05:10:53 +00005878 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005879 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5880 EPI.Variadic = false;
5881 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005882 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005883 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005884}
5885
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005886/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5887/// well-formednes of the conversion function declarator @p D with
5888/// type @p R. If there are any errors in the declarator, this routine
5889/// will emit diagnostics and return true. Otherwise, it will return
5890/// false. Either way, the type @p R will be updated to reflect a
5891/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005892void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005893 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005894 // C++ [class.conv.fct]p1:
5895 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005896 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005897 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005898 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005899 if (!D.isInvalidType())
5900 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5901 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5902 << SourceRange(D.getIdentifierLoc());
5903 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005904 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005905 }
John McCalla3f81372010-04-13 00:04:31 +00005906
5907 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5908
Chris Lattner6e475012009-04-25 08:35:12 +00005909 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005910 // Conversion functions don't have return types, but the parser will
5911 // happily parse something like:
5912 //
5913 // class X {
5914 // float operator bool();
5915 // };
5916 //
5917 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005918 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5919 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5920 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005921 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005922 }
5923
John McCalla3f81372010-04-13 00:04:31 +00005924 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5925
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005926 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005927 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005928 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5929
5930 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005931 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005932 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005933 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005934 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005935 D.setInvalidType();
5936 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005937
John McCalla3f81372010-04-13 00:04:31 +00005938 // Diagnose "&operator bool()" and other such nonsense. This
5939 // is actually a gcc extension which we don't support.
5940 if (Proto->getResultType() != ConvType) {
5941 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5942 << Proto->getResultType();
5943 D.setInvalidType();
5944 ConvType = Proto->getResultType();
5945 }
5946
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005947 // C++ [class.conv.fct]p4:
5948 // The conversion-type-id shall not represent a function type nor
5949 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005950 if (ConvType->isArrayType()) {
5951 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5952 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005953 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005954 } else if (ConvType->isFunctionType()) {
5955 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5956 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005957 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005958 }
5959
5960 // Rebuild the function type "R" without any parameters (in case any
5961 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005962 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005963 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005964 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5965 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005966
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005967 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005968 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005969 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005970 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005971 diag::warn_cxx98_compat_explicit_conversion_functions :
5972 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005973 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005974}
5975
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005976/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5977/// the declaration of the given C++ conversion function. This routine
5978/// is responsible for recording the conversion function in the C++
5979/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005980Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005981 assert(Conversion && "Expected to receive a conversion function declaration");
5982
Douglas Gregor9d350972008-12-12 08:25:50 +00005983 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005984
5985 // Make sure we aren't redeclaring the conversion function.
5986 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005987
5988 // C++ [class.conv.fct]p1:
5989 // [...] A conversion function is never used to convert a
5990 // (possibly cv-qualified) object to the (possibly cv-qualified)
5991 // same object type (or a reference to it), to a (possibly
5992 // cv-qualified) base class of that type (or a reference to it),
5993 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005994 // FIXME: Suppress this warning if the conversion function ends up being a
5995 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005996 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005997 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005998 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005999 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006000 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6001 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006002 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006003 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006004 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6005 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006006 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006007 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006008 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006009 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006010 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006011 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006012 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006013 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006014 }
6015
Douglas Gregore80622f2010-09-29 04:25:11 +00006016 if (FunctionTemplateDecl *ConversionTemplate
6017 = Conversion->getDescribedFunctionTemplate())
6018 return ConversionTemplate;
6019
John McCalld226f652010-08-21 09:40:31 +00006020 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006021}
6022
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006023//===----------------------------------------------------------------------===//
6024// Namespace Handling
6025//===----------------------------------------------------------------------===//
6026
Richard Smithd1a55a62012-10-04 22:13:39 +00006027/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6028/// reopened.
6029static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6030 SourceLocation Loc,
6031 IdentifierInfo *II, bool *IsInline,
6032 NamespaceDecl *PrevNS) {
6033 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006034
Richard Smithc969e6a2012-10-05 01:46:25 +00006035 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6036 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6037 // inline namespaces, with the intention of bringing names into namespace std.
6038 //
6039 // We support this just well enough to get that case working; this is not
6040 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006041 if (*IsInline && II && II->getName().startswith("__atomic") &&
6042 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006043 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006044 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6045 NS = NS->getPreviousDecl())
6046 NS->setInline(*IsInline);
6047 // Patch up the lookup table for the containing namespace. This isn't really
6048 // correct, but it's good enough for this particular case.
6049 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6050 E = PrevNS->decls_end(); I != E; ++I)
6051 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6052 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6053 return;
6054 }
6055
6056 if (PrevNS->isInline())
6057 // The user probably just forgot the 'inline', so suggest that it
6058 // be added back.
6059 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6060 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6061 else
6062 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6063 << IsInline;
6064
6065 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6066 *IsInline = PrevNS->isInline();
6067}
John McCallea318642010-08-26 09:15:37 +00006068
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006069/// ActOnStartNamespaceDef - This is called at the start of a namespace
6070/// definition.
John McCalld226f652010-08-21 09:40:31 +00006071Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006072 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006073 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006074 SourceLocation IdentLoc,
6075 IdentifierInfo *II,
6076 SourceLocation LBrace,
6077 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006078 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6079 // For anonymous namespace, take the location of the left brace.
6080 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006081 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006082 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006083 bool IsStd = false;
6084 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006085 Scope *DeclRegionScope = NamespcScope->getParent();
6086
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006087 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006088 if (II) {
6089 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006090 // The identifier in an original-namespace-definition shall not
6091 // have been previously defined in the declarative region in
6092 // which the original-namespace-definition appears. The
6093 // identifier in an original-namespace-definition is the name of
6094 // the namespace. Subsequently in that declarative region, it is
6095 // treated as an original-namespace-name.
6096 //
6097 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006098 // look through using directives, just look for any ordinary names.
6099
6100 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006101 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6102 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006103 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006104 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6105 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6106 ++I) {
6107 if ((*I)->getIdentifierNamespace() & IDNS) {
6108 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006109 break;
6110 }
6111 }
6112
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006113 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6114
6115 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006116 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006117 if (IsInline != PrevNS->isInline())
6118 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6119 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006120 } else if (PrevDecl) {
6121 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006122 Diag(Loc, diag::err_redefinition_different_kind)
6123 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006124 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006125 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006126 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006127 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006128 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006129 // This is the first "real" definition of the namespace "std", so update
6130 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006131 PrevNS = getStdNamespace();
6132 IsStd = true;
6133 AddToKnown = !IsInline;
6134 } else {
6135 // We've seen this namespace for the first time.
6136 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006137 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006138 } else {
John McCall9aeed322009-10-01 00:25:31 +00006139 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006140
6141 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006142 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006143 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006144 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006145 } else {
6146 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006147 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006148 }
6149
Richard Smithd1a55a62012-10-04 22:13:39 +00006150 if (PrevNS && IsInline != PrevNS->isInline())
6151 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6152 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006153 }
6154
6155 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6156 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006157 if (IsInvalid)
6158 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006159
6160 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006161
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006162 // FIXME: Should we be merging attributes?
6163 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006164 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006165
6166 if (IsStd)
6167 StdNamespace = Namespc;
6168 if (AddToKnown)
6169 KnownNamespaces[Namespc] = false;
6170
6171 if (II) {
6172 PushOnScopeChains(Namespc, DeclRegionScope);
6173 } else {
6174 // Link the anonymous namespace into its parent.
6175 DeclContext *Parent = CurContext->getRedeclContext();
6176 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6177 TU->setAnonymousNamespace(Namespc);
6178 } else {
6179 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006180 }
John McCall9aeed322009-10-01 00:25:31 +00006181
Douglas Gregora4181472010-03-24 00:46:35 +00006182 CurContext->addDecl(Namespc);
6183
John McCall9aeed322009-10-01 00:25:31 +00006184 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6185 // behaves as if it were replaced by
6186 // namespace unique { /* empty body */ }
6187 // using namespace unique;
6188 // namespace unique { namespace-body }
6189 // where all occurrences of 'unique' in a translation unit are
6190 // replaced by the same identifier and this identifier differs
6191 // from all other identifiers in the entire program.
6192
6193 // We just create the namespace with an empty name and then add an
6194 // implicit using declaration, just like the standard suggests.
6195 //
6196 // CodeGen enforces the "universally unique" aspect by giving all
6197 // declarations semantically contained within an anonymous
6198 // namespace internal linkage.
6199
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006200 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006201 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006202 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006203 /* 'using' */ LBrace,
6204 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006205 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006206 /* identifier */ SourceLocation(),
6207 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006208 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006209 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006210 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006211 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006212 }
6213
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006214 ActOnDocumentableDecl(Namespc);
6215
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006216 // Although we could have an invalid decl (i.e. the namespace name is a
6217 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006218 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6219 // for the namespace has the declarations that showed up in that particular
6220 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006221 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006222 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006223}
6224
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006225/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6226/// is a namespace alias, returns the namespace it points to.
6227static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6228 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6229 return AD->getNamespace();
6230 return dyn_cast_or_null<NamespaceDecl>(D);
6231}
6232
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006233/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6234/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006235void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006236 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6237 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006238 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006239 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006240 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006241 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006242}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006243
John McCall384aff82010-08-25 07:42:41 +00006244CXXRecordDecl *Sema::getStdBadAlloc() const {
6245 return cast_or_null<CXXRecordDecl>(
6246 StdBadAlloc.get(Context.getExternalSource()));
6247}
6248
6249NamespaceDecl *Sema::getStdNamespace() const {
6250 return cast_or_null<NamespaceDecl>(
6251 StdNamespace.get(Context.getExternalSource()));
6252}
6253
Douglas Gregor66992202010-06-29 17:53:46 +00006254/// \brief Retrieve the special "std" namespace, which may require us to
6255/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006256NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006257 if (!StdNamespace) {
6258 // The "std" namespace has not yet been defined, so build one implicitly.
6259 StdNamespace = NamespaceDecl::Create(Context,
6260 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006261 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006262 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006263 &PP.getIdentifierTable().get("std"),
6264 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006265 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006266 }
6267
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006268 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006269}
6270
Sebastian Redl395e04d2012-01-17 22:49:33 +00006271bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006272 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006273 "Looking for std::initializer_list outside of C++.");
6274
6275 // We're looking for implicit instantiations of
6276 // template <typename E> class std::initializer_list.
6277
6278 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6279 return false;
6280
Sebastian Redl84760e32012-01-17 22:49:58 +00006281 ClassTemplateDecl *Template = 0;
6282 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006283
Sebastian Redl84760e32012-01-17 22:49:58 +00006284 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006285
Sebastian Redl84760e32012-01-17 22:49:58 +00006286 ClassTemplateSpecializationDecl *Specialization =
6287 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6288 if (!Specialization)
6289 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006290
Sebastian Redl84760e32012-01-17 22:49:58 +00006291 Template = Specialization->getSpecializedTemplate();
6292 Arguments = Specialization->getTemplateArgs().data();
6293 } else if (const TemplateSpecializationType *TST =
6294 Ty->getAs<TemplateSpecializationType>()) {
6295 Template = dyn_cast_or_null<ClassTemplateDecl>(
6296 TST->getTemplateName().getAsTemplateDecl());
6297 Arguments = TST->getArgs();
6298 }
6299 if (!Template)
6300 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006301
6302 if (!StdInitializerList) {
6303 // Haven't recognized std::initializer_list yet, maybe this is it.
6304 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6305 if (TemplateClass->getIdentifier() !=
6306 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006307 !getStdNamespace()->InEnclosingNamespaceSetOf(
6308 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006309 return false;
6310 // This is a template called std::initializer_list, but is it the right
6311 // template?
6312 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006313 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006314 return false;
6315 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6316 return false;
6317
6318 // It's the right template.
6319 StdInitializerList = Template;
6320 }
6321
6322 if (Template != StdInitializerList)
6323 return false;
6324
6325 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006326 if (Element)
6327 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006328 return true;
6329}
6330
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006331static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6332 NamespaceDecl *Std = S.getStdNamespace();
6333 if (!Std) {
6334 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6335 return 0;
6336 }
6337
6338 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6339 Loc, Sema::LookupOrdinaryName);
6340 if (!S.LookupQualifiedName(Result, Std)) {
6341 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6342 return 0;
6343 }
6344 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6345 if (!Template) {
6346 Result.suppressDiagnostics();
6347 // We found something weird. Complain about the first thing we found.
6348 NamedDecl *Found = *Result.begin();
6349 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6350 return 0;
6351 }
6352
6353 // We found some template called std::initializer_list. Now verify that it's
6354 // correct.
6355 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006356 if (Params->getMinRequiredArguments() != 1 ||
6357 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006358 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6359 return 0;
6360 }
6361
6362 return Template;
6363}
6364
6365QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6366 if (!StdInitializerList) {
6367 StdInitializerList = LookupStdInitializerList(*this, Loc);
6368 if (!StdInitializerList)
6369 return QualType();
6370 }
6371
6372 TemplateArgumentListInfo Args(Loc, Loc);
6373 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6374 Context.getTrivialTypeSourceInfo(Element,
6375 Loc)));
6376 return Context.getCanonicalType(
6377 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6378}
6379
Sebastian Redl98d36062012-01-17 22:50:14 +00006380bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6381 // C++ [dcl.init.list]p2:
6382 // A constructor is an initializer-list constructor if its first parameter
6383 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6384 // std::initializer_list<E> for some type E, and either there are no other
6385 // parameters or else all other parameters have default arguments.
6386 if (Ctor->getNumParams() < 1 ||
6387 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6388 return false;
6389
6390 QualType ArgType = Ctor->getParamDecl(0)->getType();
6391 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6392 ArgType = RT->getPointeeType().getUnqualifiedType();
6393
6394 return isStdInitializerList(ArgType, 0);
6395}
6396
Douglas Gregor9172aa62011-03-26 22:25:30 +00006397/// \brief Determine whether a using statement is in a context where it will be
6398/// apply in all contexts.
6399static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6400 switch (CurContext->getDeclKind()) {
6401 case Decl::TranslationUnit:
6402 return true;
6403 case Decl::LinkageSpec:
6404 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6405 default:
6406 return false;
6407 }
6408}
6409
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006410namespace {
6411
6412// Callback to only accept typo corrections that are namespaces.
6413class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6414 public:
6415 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6416 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6417 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6418 }
6419 return false;
6420 }
6421};
6422
6423}
6424
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006425static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6426 CXXScopeSpec &SS,
6427 SourceLocation IdentLoc,
6428 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006429 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006430 R.clear();
6431 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006432 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006433 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006434 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6435 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006436 if (DeclContext *DC = S.computeDeclContext(SS, false))
6437 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6438 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006439 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6440 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006441 else
6442 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6443 << Ident << CorrectedQuotedStr
6444 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006445
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006446 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6447 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006448
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006449 R.addDecl(Corrected.getCorrectionDecl());
6450 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006451 }
6452 return false;
6453}
6454
John McCalld226f652010-08-21 09:40:31 +00006455Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006456 SourceLocation UsingLoc,
6457 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006458 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006459 SourceLocation IdentLoc,
6460 IdentifierInfo *NamespcName,
6461 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006462 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6463 assert(NamespcName && "Invalid NamespcName.");
6464 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006465
6466 // This can only happen along a recovery path.
6467 while (S->getFlags() & Scope::TemplateParamScope)
6468 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006469 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006470
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006471 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006472 NestedNameSpecifier *Qualifier = 0;
6473 if (SS.isSet())
6474 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6475
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006476 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006477 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6478 LookupParsedName(R, S, &SS);
6479 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006480 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006481
Douglas Gregor66992202010-06-29 17:53:46 +00006482 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006483 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006484 // Allow "using namespace std;" or "using namespace ::std;" even if
6485 // "std" hasn't been defined yet, for GCC compatibility.
6486 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6487 NamespcName->isStr("std")) {
6488 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006489 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006490 R.resolveKind();
6491 }
6492 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006493 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006494 }
6495
John McCallf36e02d2009-10-09 21:13:30 +00006496 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006497 NamedDecl *Named = R.getFoundDecl();
6498 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6499 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006500 // C++ [namespace.udir]p1:
6501 // A using-directive specifies that the names in the nominated
6502 // namespace can be used in the scope in which the
6503 // using-directive appears after the using-directive. During
6504 // unqualified name lookup (3.4.1), the names appear as if they
6505 // were declared in the nearest enclosing namespace which
6506 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006507 // namespace. [Note: in this context, "contains" means "contains
6508 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006509
6510 // Find enclosing context containing both using-directive and
6511 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006512 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006513 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6514 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6515 CommonAncestor = CommonAncestor->getParent();
6516
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006517 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006518 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006519 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006520
Douglas Gregor9172aa62011-03-26 22:25:30 +00006521 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006522 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006523 Diag(IdentLoc, diag::warn_using_directive_in_header);
6524 }
6525
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006526 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006527 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006528 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006529 }
6530
Richard Smith6b3d3e52013-02-20 19:22:51 +00006531 if (UDir)
6532 ProcessDeclAttributeList(S, UDir, AttrList);
6533
John McCalld226f652010-08-21 09:40:31 +00006534 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006535}
6536
6537void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006538 // If the scope has an associated entity and the using directive is at
6539 // namespace or translation unit scope, add the UsingDirectiveDecl into
6540 // its lookup structure so qualified name lookup can find it.
6541 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6542 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006543 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006544 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006545 // Otherwise, it is at block sope. The using-directives will affect lookup
6546 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006547 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006548}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006549
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006550
John McCalld226f652010-08-21 09:40:31 +00006551Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006552 AccessSpecifier AS,
6553 bool HasUsingKeyword,
6554 SourceLocation UsingLoc,
6555 CXXScopeSpec &SS,
6556 UnqualifiedId &Name,
6557 AttributeList *AttrList,
6558 bool IsTypeName,
6559 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006560 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006561
Douglas Gregor12c118a2009-11-04 16:30:06 +00006562 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006563 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006564 case UnqualifiedId::IK_Identifier:
6565 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006566 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006567 case UnqualifiedId::IK_ConversionFunctionId:
6568 break;
6569
6570 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006571 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006572 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006573 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006574 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006575 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006576 diag::err_using_decl_constructor)
6577 << SS.getRange();
6578
Richard Smith80ad52f2013-01-02 11:42:31 +00006579 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006580
John McCalld226f652010-08-21 09:40:31 +00006581 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006582
6583 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006584 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006585 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006586 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006587
6588 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006589 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006590 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006591 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006592 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006593
6594 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6595 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006596 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006597 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006598
Richard Smith07b0fdc2013-03-18 21:12:30 +00006599 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006600 // TODO: store that the declaration was written without 'using' and
6601 // talk about access decls instead of using decls in the
6602 // diagnostics.
6603 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006604 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006605
6606 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006607 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006608 }
6609
Douglas Gregor56c04582010-12-16 00:46:58 +00006610 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6611 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6612 return 0;
6613
John McCall9488ea12009-11-17 05:59:44 +00006614 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006615 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006616 /* IsInstantiation */ false,
6617 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006618 if (UD)
6619 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006620
John McCalld226f652010-08-21 09:40:31 +00006621 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006622}
6623
Douglas Gregor09acc982010-07-07 23:08:52 +00006624/// \brief Determine whether a using declaration considers the given
6625/// declarations as "equivalent", e.g., if they are redeclarations of
6626/// the same entity or are both typedefs of the same type.
6627static bool
6628IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6629 bool &SuppressRedeclaration) {
6630 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6631 SuppressRedeclaration = false;
6632 return true;
6633 }
6634
Richard Smith162e1c12011-04-15 14:24:37 +00006635 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6636 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006637 SuppressRedeclaration = true;
6638 return Context.hasSameType(TD1->getUnderlyingType(),
6639 TD2->getUnderlyingType());
6640 }
6641
6642 return false;
6643}
6644
6645
John McCall9f54ad42009-12-10 09:41:52 +00006646/// Determines whether to create a using shadow decl for a particular
6647/// decl, given the set of decls existing prior to this using lookup.
6648bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6649 const LookupResult &Previous) {
6650 // Diagnose finding a decl which is not from a base class of the
6651 // current class. We do this now because there are cases where this
6652 // function will silently decide not to build a shadow decl, which
6653 // will pre-empt further diagnostics.
6654 //
6655 // We don't need to do this in C++0x because we do the check once on
6656 // the qualifier.
6657 //
6658 // FIXME: diagnose the following if we care enough:
6659 // struct A { int foo; };
6660 // struct B : A { using A::foo; };
6661 // template <class T> struct C : A {};
6662 // template <class T> struct D : C<T> { using B::foo; } // <---
6663 // This is invalid (during instantiation) in C++03 because B::foo
6664 // resolves to the using decl in B, which is not a base class of D<T>.
6665 // We can't diagnose it immediately because C<T> is an unknown
6666 // specialization. The UsingShadowDecl in D<T> then points directly
6667 // to A::foo, which will look well-formed when we instantiate.
6668 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006669 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006670 DeclContext *OrigDC = Orig->getDeclContext();
6671
6672 // Handle enums and anonymous structs.
6673 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6674 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6675 while (OrigRec->isAnonymousStructOrUnion())
6676 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6677
6678 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6679 if (OrigDC == CurContext) {
6680 Diag(Using->getLocation(),
6681 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006682 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006683 Diag(Orig->getLocation(), diag::note_using_decl_target);
6684 return true;
6685 }
6686
Douglas Gregordc355712011-02-25 00:36:19 +00006687 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006688 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006689 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006690 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006691 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006692 Diag(Orig->getLocation(), diag::note_using_decl_target);
6693 return true;
6694 }
6695 }
6696
6697 if (Previous.empty()) return false;
6698
6699 NamedDecl *Target = Orig;
6700 if (isa<UsingShadowDecl>(Target))
6701 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6702
John McCalld7533ec2009-12-11 02:33:26 +00006703 // If the target happens to be one of the previous declarations, we
6704 // don't have a conflict.
6705 //
6706 // FIXME: but we might be increasing its access, in which case we
6707 // should redeclare it.
6708 NamedDecl *NonTag = 0, *Tag = 0;
6709 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6710 I != E; ++I) {
6711 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006712 bool Result;
6713 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6714 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006715
6716 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6717 }
6718
John McCall9f54ad42009-12-10 09:41:52 +00006719 if (Target->isFunctionOrFunctionTemplate()) {
6720 FunctionDecl *FD;
6721 if (isa<FunctionTemplateDecl>(Target))
6722 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6723 else
6724 FD = cast<FunctionDecl>(Target);
6725
6726 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006727 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006728 case Ovl_Overload:
6729 return false;
6730
6731 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006732 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006733 break;
6734
6735 // We found a decl with the exact signature.
6736 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006737 // If we're in a record, we want to hide the target, so we
6738 // return true (without a diagnostic) to tell the caller not to
6739 // build a shadow decl.
6740 if (CurContext->isRecord())
6741 return true;
6742
6743 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006744 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006745 break;
6746 }
6747
6748 Diag(Target->getLocation(), diag::note_using_decl_target);
6749 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6750 return true;
6751 }
6752
6753 // Target is not a function.
6754
John McCall9f54ad42009-12-10 09:41:52 +00006755 if (isa<TagDecl>(Target)) {
6756 // No conflict between a tag and a non-tag.
6757 if (!Tag) return false;
6758
John McCall41ce66f2009-12-10 19:51:03 +00006759 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006760 Diag(Target->getLocation(), diag::note_using_decl_target);
6761 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6762 return true;
6763 }
6764
6765 // No conflict between a tag and a non-tag.
6766 if (!NonTag) return false;
6767
John McCall41ce66f2009-12-10 19:51:03 +00006768 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006769 Diag(Target->getLocation(), diag::note_using_decl_target);
6770 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6771 return true;
6772}
6773
John McCall9488ea12009-11-17 05:59:44 +00006774/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006775UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006776 UsingDecl *UD,
6777 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006778
6779 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006780 NamedDecl *Target = Orig;
6781 if (isa<UsingShadowDecl>(Target)) {
6782 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6783 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006784 }
6785
6786 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006787 = UsingShadowDecl::Create(Context, CurContext,
6788 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006789 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006790
6791 Shadow->setAccess(UD->getAccess());
6792 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6793 Shadow->setInvalidDecl();
6794
John McCall9488ea12009-11-17 05:59:44 +00006795 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006796 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006797 else
John McCall604e7f12009-12-08 07:46:18 +00006798 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006799
John McCall604e7f12009-12-08 07:46:18 +00006800
John McCall9f54ad42009-12-10 09:41:52 +00006801 return Shadow;
6802}
John McCall604e7f12009-12-08 07:46:18 +00006803
John McCall9f54ad42009-12-10 09:41:52 +00006804/// Hides a using shadow declaration. This is required by the current
6805/// using-decl implementation when a resolvable using declaration in a
6806/// class is followed by a declaration which would hide or override
6807/// one or more of the using decl's targets; for example:
6808///
6809/// struct Base { void foo(int); };
6810/// struct Derived : Base {
6811/// using Base::foo;
6812/// void foo(int);
6813/// };
6814///
6815/// The governing language is C++03 [namespace.udecl]p12:
6816///
6817/// When a using-declaration brings names from a base class into a
6818/// derived class scope, member functions in the derived class
6819/// override and/or hide member functions with the same name and
6820/// parameter types in a base class (rather than conflicting).
6821///
6822/// There are two ways to implement this:
6823/// (1) optimistically create shadow decls when they're not hidden
6824/// by existing declarations, or
6825/// (2) don't create any shadow decls (or at least don't make them
6826/// visible) until we've fully parsed/instantiated the class.
6827/// The problem with (1) is that we might have to retroactively remove
6828/// a shadow decl, which requires several O(n) operations because the
6829/// decl structures are (very reasonably) not designed for removal.
6830/// (2) avoids this but is very fiddly and phase-dependent.
6831void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006832 if (Shadow->getDeclName().getNameKind() ==
6833 DeclarationName::CXXConversionFunctionName)
6834 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6835
John McCall9f54ad42009-12-10 09:41:52 +00006836 // Remove it from the DeclContext...
6837 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006838
John McCall9f54ad42009-12-10 09:41:52 +00006839 // ...and the scope, if applicable...
6840 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006841 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006842 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006843 }
6844
John McCall9f54ad42009-12-10 09:41:52 +00006845 // ...and the using decl.
6846 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6847
6848 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006849 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006850}
6851
John McCall7ba107a2009-11-18 02:36:19 +00006852/// Builds a using declaration.
6853///
6854/// \param IsInstantiation - Whether this call arises from an
6855/// instantiation of an unresolved using declaration. We treat
6856/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006857NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6858 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006859 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006860 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006861 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006862 bool IsInstantiation,
6863 bool IsTypeName,
6864 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006865 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006866 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006867 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006868
Anders Carlsson550b14b2009-08-28 05:49:21 +00006869 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006870
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006871 if (SS.isEmpty()) {
6872 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006873 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006874 }
Mike Stump1eb44332009-09-09 15:08:12 +00006875
John McCall9f54ad42009-12-10 09:41:52 +00006876 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006877 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006878 ForRedeclaration);
6879 Previous.setHideTags(false);
6880 if (S) {
6881 LookupName(Previous, S);
6882
6883 // It is really dumb that we have to do this.
6884 LookupResult::Filter F = Previous.makeFilter();
6885 while (F.hasNext()) {
6886 NamedDecl *D = F.next();
6887 if (!isDeclInScope(D, CurContext, S))
6888 F.erase();
6889 }
6890 F.done();
6891 } else {
6892 assert(IsInstantiation && "no scope in non-instantiation");
6893 assert(CurContext->isRecord() && "scope not record in instantiation");
6894 LookupQualifiedName(Previous, CurContext);
6895 }
6896
John McCall9f54ad42009-12-10 09:41:52 +00006897 // Check for invalid redeclarations.
6898 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6899 return 0;
6900
6901 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006902 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6903 return 0;
6904
John McCallaf8e6ed2009-11-12 03:15:40 +00006905 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006906 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006907 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006908 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006909 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006910 // FIXME: not all declaration name kinds are legal here
6911 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6912 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006913 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006914 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006915 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006916 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6917 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006918 }
John McCalled976492009-12-04 22:46:56 +00006919 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006920 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6921 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006922 }
John McCalled976492009-12-04 22:46:56 +00006923 D->setAccess(AS);
6924 CurContext->addDecl(D);
6925
6926 if (!LookupContext) return D;
6927 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006928
John McCall77bb1aa2010-05-01 00:40:08 +00006929 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006930 UD->setInvalidDecl();
6931 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006932 }
6933
Richard Smithc5a89a12012-04-02 01:30:27 +00006934 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006935 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006936 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006937 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006938 return UD;
6939 }
6940
6941 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006942
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006943 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006944
John McCall604e7f12009-12-08 07:46:18 +00006945 // Unlike most lookups, we don't always want to hide tag
6946 // declarations: tag names are visible through the using declaration
6947 // even if hidden by ordinary names, *except* in a dependent context
6948 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006949 if (!IsInstantiation)
6950 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006951
John McCallb9abd8722012-04-07 03:04:20 +00006952 // For the purposes of this lookup, we have a base object type
6953 // equal to that of the current context.
6954 if (CurContext->isRecord()) {
6955 R.setBaseObjectType(
6956 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6957 }
6958
John McCalla24dc2e2009-11-17 02:14:36 +00006959 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006960
John McCallf36e02d2009-10-09 21:13:30 +00006961 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006962 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006963 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006964 UD->setInvalidDecl();
6965 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006966 }
6967
John McCalled976492009-12-04 22:46:56 +00006968 if (R.isAmbiguous()) {
6969 UD->setInvalidDecl();
6970 return UD;
6971 }
Mike Stump1eb44332009-09-09 15:08:12 +00006972
John McCall7ba107a2009-11-18 02:36:19 +00006973 if (IsTypeName) {
6974 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006975 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006976 Diag(IdentLoc, diag::err_using_typename_non_type);
6977 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6978 Diag((*I)->getUnderlyingDecl()->getLocation(),
6979 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006980 UD->setInvalidDecl();
6981 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006982 }
6983 } else {
6984 // If we asked for a non-typename and we got a type, error out,
6985 // but only if this is an instantiation of an unresolved using
6986 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006987 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006988 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6989 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006990 UD->setInvalidDecl();
6991 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006992 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006993 }
6994
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006995 // C++0x N2914 [namespace.udecl]p6:
6996 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006997 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006998 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6999 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007000 UD->setInvalidDecl();
7001 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007002 }
Mike Stump1eb44332009-09-09 15:08:12 +00007003
John McCall9f54ad42009-12-10 09:41:52 +00007004 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7005 if (!CheckUsingShadowDecl(UD, *I, Previous))
7006 BuildUsingShadowDecl(S, UD, *I);
7007 }
John McCall9488ea12009-11-17 05:59:44 +00007008
7009 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007010}
7011
Sebastian Redlf677ea32011-02-05 19:23:19 +00007012/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007013bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7014 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007015
Douglas Gregordc355712011-02-25 00:36:19 +00007016 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007017 assert(SourceType &&
7018 "Using decl naming constructor doesn't have type in scope spec.");
7019 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7020
7021 // Check whether the named type is a direct base class.
7022 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7023 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7024 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7025 BaseIt != BaseE; ++BaseIt) {
7026 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7027 if (CanonicalSourceType == BaseType)
7028 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007029 if (BaseIt->getType()->isDependentType())
7030 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007031 }
7032
7033 if (BaseIt == BaseE) {
7034 // Did not find SourceType in the bases.
7035 Diag(UD->getUsingLocation(),
7036 diag::err_using_decl_constructor_not_in_direct_base)
7037 << UD->getNameInfo().getSourceRange()
7038 << QualType(SourceType, 0) << TargetClass;
7039 return true;
7040 }
7041
Richard Smithc5a89a12012-04-02 01:30:27 +00007042 if (!CurContext->isDependentContext())
7043 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007044
7045 return false;
7046}
7047
John McCall9f54ad42009-12-10 09:41:52 +00007048/// Checks that the given using declaration is not an invalid
7049/// redeclaration. Note that this is checking only for the using decl
7050/// itself, not for any ill-formedness among the UsingShadowDecls.
7051bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7052 bool isTypeName,
7053 const CXXScopeSpec &SS,
7054 SourceLocation NameLoc,
7055 const LookupResult &Prev) {
7056 // C++03 [namespace.udecl]p8:
7057 // C++0x [namespace.udecl]p10:
7058 // A using-declaration is a declaration and can therefore be used
7059 // repeatedly where (and only where) multiple declarations are
7060 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007061 //
John McCall8a726212010-11-29 18:01:58 +00007062 // That's in non-member contexts.
7063 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007064 return false;
7065
7066 NestedNameSpecifier *Qual
7067 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7068
7069 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7070 NamedDecl *D = *I;
7071
7072 bool DTypename;
7073 NestedNameSpecifier *DQual;
7074 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7075 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007076 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007077 } else if (UnresolvedUsingValueDecl *UD
7078 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7079 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007080 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007081 } else if (UnresolvedUsingTypenameDecl *UD
7082 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7083 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007084 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007085 } else continue;
7086
7087 // using decls differ if one says 'typename' and the other doesn't.
7088 // FIXME: non-dependent using decls?
7089 if (isTypeName != DTypename) continue;
7090
7091 // using decls differ if they name different scopes (but note that
7092 // template instantiation can cause this check to trigger when it
7093 // didn't before instantiation).
7094 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7095 Context.getCanonicalNestedNameSpecifier(DQual))
7096 continue;
7097
7098 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007099 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007100 return true;
7101 }
7102
7103 return false;
7104}
7105
John McCall604e7f12009-12-08 07:46:18 +00007106
John McCalled976492009-12-04 22:46:56 +00007107/// Checks that the given nested-name qualifier used in a using decl
7108/// in the current context is appropriately related to the current
7109/// scope. If an error is found, diagnoses it and returns true.
7110bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7111 const CXXScopeSpec &SS,
7112 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007113 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007114
John McCall604e7f12009-12-08 07:46:18 +00007115 if (!CurContext->isRecord()) {
7116 // C++03 [namespace.udecl]p3:
7117 // C++0x [namespace.udecl]p8:
7118 // A using-declaration for a class member shall be a member-declaration.
7119
7120 // If we weren't able to compute a valid scope, it must be a
7121 // dependent class scope.
7122 if (!NamedContext || NamedContext->isRecord()) {
7123 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7124 << SS.getRange();
7125 return true;
7126 }
7127
7128 // Otherwise, everything is known to be fine.
7129 return false;
7130 }
7131
7132 // The current scope is a record.
7133
7134 // If the named context is dependent, we can't decide much.
7135 if (!NamedContext) {
7136 // FIXME: in C++0x, we can diagnose if we can prove that the
7137 // nested-name-specifier does not refer to a base class, which is
7138 // still possible in some cases.
7139
7140 // Otherwise we have to conservatively report that things might be
7141 // okay.
7142 return false;
7143 }
7144
7145 if (!NamedContext->isRecord()) {
7146 // Ideally this would point at the last name in the specifier,
7147 // but we don't have that level of source info.
7148 Diag(SS.getRange().getBegin(),
7149 diag::err_using_decl_nested_name_specifier_is_not_class)
7150 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7151 return true;
7152 }
7153
Douglas Gregor6fb07292010-12-21 07:41:49 +00007154 if (!NamedContext->isDependentContext() &&
7155 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7156 return true;
7157
Richard Smith80ad52f2013-01-02 11:42:31 +00007158 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007159 // C++0x [namespace.udecl]p3:
7160 // In a using-declaration used as a member-declaration, the
7161 // nested-name-specifier shall name a base class of the class
7162 // being defined.
7163
7164 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7165 cast<CXXRecordDecl>(NamedContext))) {
7166 if (CurContext == NamedContext) {
7167 Diag(NameLoc,
7168 diag::err_using_decl_nested_name_specifier_is_current_class)
7169 << SS.getRange();
7170 return true;
7171 }
7172
7173 Diag(SS.getRange().getBegin(),
7174 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7175 << (NestedNameSpecifier*) SS.getScopeRep()
7176 << cast<CXXRecordDecl>(CurContext)
7177 << SS.getRange();
7178 return true;
7179 }
7180
7181 return false;
7182 }
7183
7184 // C++03 [namespace.udecl]p4:
7185 // A using-declaration used as a member-declaration shall refer
7186 // to a member of a base class of the class being defined [etc.].
7187
7188 // Salient point: SS doesn't have to name a base class as long as
7189 // lookup only finds members from base classes. Therefore we can
7190 // diagnose here only if we can prove that that can't happen,
7191 // i.e. if the class hierarchies provably don't intersect.
7192
7193 // TODO: it would be nice if "definitely valid" results were cached
7194 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7195 // need to be repeated.
7196
7197 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007198 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007199
7200 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7201 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7202 Data->Bases.insert(Base);
7203 return true;
7204 }
7205
7206 bool hasDependentBases(const CXXRecordDecl *Class) {
7207 return !Class->forallBases(collect, this);
7208 }
7209
7210 /// Returns true if the base is dependent or is one of the
7211 /// accumulated base classes.
7212 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7213 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7214 return !Data->Bases.count(Base);
7215 }
7216
7217 bool mightShareBases(const CXXRecordDecl *Class) {
7218 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7219 }
7220 };
7221
7222 UserData Data;
7223
7224 // Returns false if we find a dependent base.
7225 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7226 return false;
7227
7228 // Returns false if the class has a dependent base or if it or one
7229 // of its bases is present in the base set of the current context.
7230 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7231 return false;
7232
7233 Diag(SS.getRange().getBegin(),
7234 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7235 << (NestedNameSpecifier*) SS.getScopeRep()
7236 << cast<CXXRecordDecl>(CurContext)
7237 << SS.getRange();
7238
7239 return true;
John McCalled976492009-12-04 22:46:56 +00007240}
7241
Richard Smith162e1c12011-04-15 14:24:37 +00007242Decl *Sema::ActOnAliasDeclaration(Scope *S,
7243 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007244 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007245 SourceLocation UsingLoc,
7246 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007247 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007248 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007249 // Skip up to the relevant declaration scope.
7250 while (S->getFlags() & Scope::TemplateParamScope)
7251 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007252 assert((S->getFlags() & Scope::DeclScope) &&
7253 "got alias-declaration outside of declaration scope");
7254
7255 if (Type.isInvalid())
7256 return 0;
7257
7258 bool Invalid = false;
7259 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7260 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007261 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007262
7263 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7264 return 0;
7265
7266 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007267 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007268 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007269 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7270 TInfo->getTypeLoc().getBeginLoc());
7271 }
Richard Smith162e1c12011-04-15 14:24:37 +00007272
7273 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7274 LookupName(Previous, S);
7275
7276 // Warn about shadowing the name of a template parameter.
7277 if (Previous.isSingleResult() &&
7278 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007279 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007280 Previous.clear();
7281 }
7282
7283 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7284 "name in alias declaration must be an identifier");
7285 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7286 Name.StartLocation,
7287 Name.Identifier, TInfo);
7288
7289 NewTD->setAccess(AS);
7290
7291 if (Invalid)
7292 NewTD->setInvalidDecl();
7293
Richard Smith6b3d3e52013-02-20 19:22:51 +00007294 ProcessDeclAttributeList(S, NewTD, AttrList);
7295
Richard Smith3e4c6c42011-05-05 21:57:07 +00007296 CheckTypedefForVariablyModifiedType(S, NewTD);
7297 Invalid |= NewTD->isInvalidDecl();
7298
Richard Smith162e1c12011-04-15 14:24:37 +00007299 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007300
7301 NamedDecl *NewND;
7302 if (TemplateParamLists.size()) {
7303 TypeAliasTemplateDecl *OldDecl = 0;
7304 TemplateParameterList *OldTemplateParams = 0;
7305
7306 if (TemplateParamLists.size() != 1) {
7307 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007308 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7309 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007310 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007311 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007312
7313 // Only consider previous declarations in the same scope.
7314 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7315 /*ExplicitInstantiationOrSpecialization*/false);
7316 if (!Previous.empty()) {
7317 Redeclaration = true;
7318
7319 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7320 if (!OldDecl && !Invalid) {
7321 Diag(UsingLoc, diag::err_redefinition_different_kind)
7322 << Name.Identifier;
7323
7324 NamedDecl *OldD = Previous.getRepresentativeDecl();
7325 if (OldD->getLocation().isValid())
7326 Diag(OldD->getLocation(), diag::note_previous_definition);
7327
7328 Invalid = true;
7329 }
7330
7331 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7332 if (TemplateParameterListsAreEqual(TemplateParams,
7333 OldDecl->getTemplateParameters(),
7334 /*Complain=*/true,
7335 TPL_TemplateMatch))
7336 OldTemplateParams = OldDecl->getTemplateParameters();
7337 else
7338 Invalid = true;
7339
7340 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7341 if (!Invalid &&
7342 !Context.hasSameType(OldTD->getUnderlyingType(),
7343 NewTD->getUnderlyingType())) {
7344 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7345 // but we can't reasonably accept it.
7346 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7347 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7348 if (OldTD->getLocation().isValid())
7349 Diag(OldTD->getLocation(), diag::note_previous_definition);
7350 Invalid = true;
7351 }
7352 }
7353 }
7354
7355 // Merge any previous default template arguments into our parameters,
7356 // and check the parameter list.
7357 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7358 TPC_TypeAliasTemplate))
7359 return 0;
7360
7361 TypeAliasTemplateDecl *NewDecl =
7362 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7363 Name.Identifier, TemplateParams,
7364 NewTD);
7365
7366 NewDecl->setAccess(AS);
7367
7368 if (Invalid)
7369 NewDecl->setInvalidDecl();
7370 else if (OldDecl)
7371 NewDecl->setPreviousDeclaration(OldDecl);
7372
7373 NewND = NewDecl;
7374 } else {
7375 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7376 NewND = NewTD;
7377 }
Richard Smith162e1c12011-04-15 14:24:37 +00007378
7379 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007380 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007381
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007382 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007383 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007384}
7385
John McCalld226f652010-08-21 09:40:31 +00007386Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007387 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007388 SourceLocation AliasLoc,
7389 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007390 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007391 SourceLocation IdentLoc,
7392 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007393
Anders Carlsson81c85c42009-03-28 23:53:49 +00007394 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007395 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7396 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007397
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007398 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007399 NamedDecl *PrevDecl
7400 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7401 ForRedeclaration);
7402 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7403 PrevDecl = 0;
7404
7405 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007406 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007407 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007408 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007409 // FIXME: At some point, we'll want to create the (redundant)
7410 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007411 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007412 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007413 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007414 }
Mike Stump1eb44332009-09-09 15:08:12 +00007415
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007416 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7417 diag::err_redefinition_different_kind;
7418 Diag(AliasLoc, DiagID) << Alias;
7419 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007420 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007421 }
7422
John McCalla24dc2e2009-11-17 02:14:36 +00007423 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007424 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007425
John McCallf36e02d2009-10-09 21:13:30 +00007426 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007427 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007428 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007429 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007430 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007431 }
Mike Stump1eb44332009-09-09 15:08:12 +00007432
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007433 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007434 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007435 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007436 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007437
John McCall3dbd3d52010-02-16 06:53:13 +00007438 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007439 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007440}
7441
Sean Hunt001cad92011-05-10 00:49:42 +00007442Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007443Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7444 CXXMethodDecl *MD) {
7445 CXXRecordDecl *ClassDecl = MD->getParent();
7446
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007447 // C++ [except.spec]p14:
7448 // An implicitly declared special member function (Clause 12) shall have an
7449 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007450 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007451 if (ClassDecl->isInvalidDecl())
7452 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007453
Sebastian Redl60618fa2011-03-12 11:50:43 +00007454 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007455 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7456 BEnd = ClassDecl->bases_end();
7457 B != BEnd; ++B) {
7458 if (B->isVirtual()) // Handled below.
7459 continue;
7460
Douglas Gregor18274032010-07-03 00:47:00 +00007461 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7462 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007463 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7464 // If this is a deleted function, add it anyway. This might be conformant
7465 // with the standard. This might not. I'm not sure. It might not matter.
7466 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007467 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007468 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007469 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007470
7471 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007472 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7473 BEnd = ClassDecl->vbases_end();
7474 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007475 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7476 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007477 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7478 // If this is a deleted function, add it anyway. This might be conformant
7479 // with the standard. This might not. I'm not sure. It might not matter.
7480 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007481 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007482 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007483 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007484
7485 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007486 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7487 FEnd = ClassDecl->field_end();
7488 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007489 if (F->hasInClassInitializer()) {
7490 if (Expr *E = F->getInClassInitializer())
7491 ExceptSpec.CalledExpr(E);
7492 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007493 // DR1351:
7494 // If the brace-or-equal-initializer of a non-static data member
7495 // invokes a defaulted default constructor of its class or of an
7496 // enclosing class in a potentially evaluated subexpression, the
7497 // program is ill-formed.
7498 //
7499 // This resolution is unworkable: the exception specification of the
7500 // default constructor can be needed in an unevaluated context, in
7501 // particular, in the operand of a noexcept-expression, and we can be
7502 // unable to compute an exception specification for an enclosed class.
7503 //
7504 // We do not allow an in-class initializer to require the evaluation
7505 // of the exception specification for any in-class initializer whose
7506 // definition is not lexically complete.
7507 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007508 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007509 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007510 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7511 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7512 // If this is a deleted function, add it anyway. This might be conformant
7513 // with the standard. This might not. I'm not sure. It might not matter.
7514 // In particular, the problem is that this function never gets called. It
7515 // might just be ill-formed because this function attempts to refer to
7516 // a deleted function here.
7517 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007518 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007519 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007520 }
John McCalle23cf432010-12-14 08:05:40 +00007521
Sean Hunt001cad92011-05-10 00:49:42 +00007522 return ExceptSpec;
7523}
7524
Richard Smith07b0fdc2013-03-18 21:12:30 +00007525Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007526Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7527 CXXRecordDecl *ClassDecl = CD->getParent();
7528
7529 // C++ [except.spec]p14:
7530 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007531 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007532 if (ClassDecl->isInvalidDecl())
7533 return ExceptSpec;
7534
7535 // Inherited constructor.
7536 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7537 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7538 // FIXME: Copying or moving the parameters could add extra exceptions to the
7539 // set, as could the default arguments for the inherited constructor. This
7540 // will be addressed when we implement the resolution of core issue 1351.
7541 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7542
7543 // Direct base-class constructors.
7544 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7545 BEnd = ClassDecl->bases_end();
7546 B != BEnd; ++B) {
7547 if (B->isVirtual()) // Handled below.
7548 continue;
7549
7550 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7551 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7552 if (BaseClassDecl == InheritedDecl)
7553 continue;
7554 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7555 if (Constructor)
7556 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7557 }
7558 }
7559
7560 // Virtual base-class constructors.
7561 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7562 BEnd = ClassDecl->vbases_end();
7563 B != BEnd; ++B) {
7564 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7565 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7566 if (BaseClassDecl == InheritedDecl)
7567 continue;
7568 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7569 if (Constructor)
7570 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7571 }
7572 }
7573
7574 // Field constructors.
7575 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7576 FEnd = ClassDecl->field_end();
7577 F != FEnd; ++F) {
7578 if (F->hasInClassInitializer()) {
7579 if (Expr *E = F->getInClassInitializer())
7580 ExceptSpec.CalledExpr(E);
7581 else if (!F->isInvalidDecl())
7582 Diag(CD->getLocation(),
7583 diag::err_in_class_initializer_references_def_ctor) << CD;
7584 } else if (const RecordType *RecordTy
7585 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7586 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7587 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7588 if (Constructor)
7589 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7590 }
7591 }
7592
Richard Smith07b0fdc2013-03-18 21:12:30 +00007593 return ExceptSpec;
7594}
7595
Richard Smithafb49182012-11-29 01:34:07 +00007596namespace {
7597/// RAII object to register a special member as being currently declared.
7598struct DeclaringSpecialMember {
7599 Sema &S;
7600 Sema::SpecialMemberDecl D;
7601 bool WasAlreadyBeingDeclared;
7602
7603 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7604 : S(S), D(RD, CSM) {
7605 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7606 if (WasAlreadyBeingDeclared)
7607 // This almost never happens, but if it does, ensure that our cache
7608 // doesn't contain a stale result.
7609 S.SpecialMemberCache.clear();
7610
7611 // FIXME: Register a note to be produced if we encounter an error while
7612 // declaring the special member.
7613 }
7614 ~DeclaringSpecialMember() {
7615 if (!WasAlreadyBeingDeclared)
7616 S.SpecialMembersBeingDeclared.erase(D);
7617 }
7618
7619 /// \brief Are we already trying to declare this special member?
7620 bool isAlreadyBeingDeclared() const {
7621 return WasAlreadyBeingDeclared;
7622 }
7623};
7624}
7625
Sean Hunt001cad92011-05-10 00:49:42 +00007626CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7627 CXXRecordDecl *ClassDecl) {
7628 // C++ [class.ctor]p5:
7629 // A default constructor for a class X is a constructor of class X
7630 // that can be called without an argument. If there is no
7631 // user-declared constructor for class X, a default constructor is
7632 // implicitly declared. An implicitly-declared default constructor
7633 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007634 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007635 "Should not build implicit default constructor!");
7636
Richard Smithafb49182012-11-29 01:34:07 +00007637 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7638 if (DSM.isAlreadyBeingDeclared())
7639 return 0;
7640
Richard Smith7756afa2012-06-10 05:43:50 +00007641 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7642 CXXDefaultConstructor,
7643 false);
7644
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007645 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007646 CanQualType ClassType
7647 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007648 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007649 DeclarationName Name
7650 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007651 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007652 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007653 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007654 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007655 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007656 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007657 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007658 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007659
7660 // Build an exception specification pointing back at this constructor.
7661 FunctionProtoType::ExtProtoInfo EPI;
7662 EPI.ExceptionSpecType = EST_Unevaluated;
7663 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007664 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7665 ArrayRef<QualType>(),
7666 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007667
Richard Smithbc2a35d2012-12-08 08:32:28 +00007668 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7669 // constructors is easy to compute.
7670 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7671
7672 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007673 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007674
Douglas Gregor18274032010-07-03 00:47:00 +00007675 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007676 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007677
Douglas Gregor23c94db2010-07-02 17:43:08 +00007678 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007679 PushOnScopeChains(DefaultCon, S, false);
7680 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007681
Douglas Gregor32df23e2010-07-01 22:02:46 +00007682 return DefaultCon;
7683}
7684
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007685void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7686 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007687 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007688 !Constructor->doesThisDeclarationHaveABody() &&
7689 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007690 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007691
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007692 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007693 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007694
Eli Friedman9a14db32012-10-18 20:14:08 +00007695 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007696 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007697 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007698 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007699 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007700 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007701 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007702 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007703 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007704
7705 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007706 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007707
7708 Constructor->setUsed();
7709 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007710
7711 if (ASTMutationListener *L = getASTMutationListener()) {
7712 L->CompletedImplicitDefinition(Constructor);
7713 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007714}
7715
Richard Smith7a614d82011-06-11 17:19:42 +00007716void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007717 // Check that any explicitly-defaulted methods have exception specifications
7718 // compatible with their implicit exception specifications.
7719 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007720}
7721
Richard Smith4841ca52013-04-10 05:48:59 +00007722namespace {
7723/// Information on inheriting constructors to declare.
7724class InheritingConstructorInfo {
7725public:
7726 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7727 : SemaRef(SemaRef), Derived(Derived) {
7728 // Mark the constructors that we already have in the derived class.
7729 //
7730 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7731 // unless there is a user-declared constructor with the same signature in
7732 // the class where the using-declaration appears.
7733 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7734 }
7735
7736 void inheritAll(CXXRecordDecl *RD) {
7737 visitAll(RD, &InheritingConstructorInfo::inherit);
7738 }
7739
7740private:
7741 /// Information about an inheriting constructor.
7742 struct InheritingConstructor {
7743 InheritingConstructor()
7744 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7745
7746 /// If \c true, a constructor with this signature is already declared
7747 /// in the derived class.
7748 bool DeclaredInDerived;
7749
7750 /// The constructor which is inherited.
7751 const CXXConstructorDecl *BaseCtor;
7752
7753 /// The derived constructor we declared.
7754 CXXConstructorDecl *DerivedCtor;
7755 };
7756
7757 /// Inheriting constructors with a given canonical type. There can be at
7758 /// most one such non-template constructor, and any number of templated
7759 /// constructors.
7760 struct InheritingConstructorsForType {
7761 InheritingConstructor NonTemplate;
7762 llvm::SmallVector<
7763 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7764
7765 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7766 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7767 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7768 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7769 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7770 false, S.TPL_TemplateMatch))
7771 return Templates[I].second;
7772 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7773 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007774 }
Richard Smith4841ca52013-04-10 05:48:59 +00007775
7776 return NonTemplate;
7777 }
7778 };
7779
7780 /// Get or create the inheriting constructor record for a constructor.
7781 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7782 QualType CtorType) {
7783 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7784 .getEntry(SemaRef, Ctor);
7785 }
7786
7787 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7788
7789 /// Process all constructors for a class.
7790 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7791 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7792 CtorE = RD->ctor_end();
7793 CtorIt != CtorE; ++CtorIt)
7794 (this->*Callback)(*CtorIt);
7795 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7796 I(RD->decls_begin()), E(RD->decls_end());
7797 I != E; ++I) {
7798 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7799 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7800 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007801 }
7802 }
Richard Smith4841ca52013-04-10 05:48:59 +00007803
7804 /// Note that a constructor (or constructor template) was declared in Derived.
7805 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7806 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7807 }
7808
7809 /// Inherit a single constructor.
7810 void inherit(const CXXConstructorDecl *Ctor) {
7811 const FunctionProtoType *CtorType =
7812 Ctor->getType()->castAs<FunctionProtoType>();
7813 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7814 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7815
7816 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7817
7818 // Core issue (no number yet): the ellipsis is always discarded.
7819 if (EPI.Variadic) {
7820 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7821 SemaRef.Diag(Ctor->getLocation(),
7822 diag::note_using_decl_constructor_ellipsis);
7823 EPI.Variadic = false;
7824 }
7825
7826 // Declare a constructor for each number of parameters.
7827 //
7828 // C++11 [class.inhctor]p1:
7829 // The candidate set of inherited constructors from the class X named in
7830 // the using-declaration consists of [... modulo defects ...] for each
7831 // constructor or constructor template of X, the set of constructors or
7832 // constructor templates that results from omitting any ellipsis parameter
7833 // specification and successively omitting parameters with a default
7834 // argument from the end of the parameter-type-list
7835 for (unsigned Params = std::max(minParamsToInherit(Ctor),
7836 Ctor->getMinRequiredArguments()),
7837 MaxParams = Ctor->getNumParams();
7838 Params <= MaxParams; ++Params)
7839 declareCtor(UsingLoc, Ctor,
7840 SemaRef.Context.getFunctionType(
7841 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7842 }
7843
7844 /// Find the using-declaration which specified that we should inherit the
7845 /// constructors of \p Base.
7846 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7847 // No fancy lookup required; just look for the base constructor name
7848 // directly within the derived class.
7849 ASTContext &Context = SemaRef.Context;
7850 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7851 Context.getCanonicalType(Context.getRecordType(Base)));
7852 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7853 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7854 }
7855
7856 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7857 // C++11 [class.inhctor]p3:
7858 // [F]or each constructor template in the candidate set of inherited
7859 // constructors, a constructor template is implicitly declared
7860 if (Ctor->getDescribedFunctionTemplate())
7861 return 0;
7862
7863 // For each non-template constructor in the candidate set of inherited
7864 // constructors other than a constructor having no parameters or a
7865 // copy/move constructor having a single parameter, a constructor is
7866 // implicitly declared [...]
7867 if (Ctor->getNumParams() == 0)
7868 return 1;
7869 if (Ctor->isCopyOrMoveConstructor())
7870 return 2;
7871
7872 // Per discussion on core reflector, never inherit a constructor which
7873 // would become a default, copy, or move constructor of Derived either.
7874 const ParmVarDecl *PD = Ctor->getParamDecl(0);
7875 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
7876 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
7877 }
7878
7879 /// Declare a single inheriting constructor, inheriting the specified
7880 /// constructor, with the given type.
7881 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
7882 QualType DerivedType) {
7883 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
7884
7885 // C++11 [class.inhctor]p3:
7886 // ... a constructor is implicitly declared with the same constructor
7887 // characteristics unless there is a user-declared constructor with
7888 // the same signature in the class where the using-declaration appears
7889 if (Entry.DeclaredInDerived)
7890 return;
7891
7892 // C++11 [class.inhctor]p7:
7893 // If two using-declarations declare inheriting constructors with the
7894 // same signature, the program is ill-formed
7895 if (Entry.DerivedCtor) {
7896 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
7897 // Only diagnose this once per constructor.
7898 if (Entry.DerivedCtor->isInvalidDecl())
7899 return;
7900 Entry.DerivedCtor->setInvalidDecl();
7901
7902 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7903 SemaRef.Diag(BaseCtor->getLocation(),
7904 diag::note_using_decl_constructor_conflict_current_ctor);
7905 SemaRef.Diag(Entry.BaseCtor->getLocation(),
7906 diag::note_using_decl_constructor_conflict_previous_ctor);
7907 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
7908 diag::note_using_decl_constructor_conflict_previous_using);
7909 } else {
7910 // Core issue (no number): if the same inheriting constructor is
7911 // produced by multiple base class constructors from the same base
7912 // class, the inheriting constructor is defined as deleted.
7913 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
7914 }
7915
7916 return;
7917 }
7918
7919 ASTContext &Context = SemaRef.Context;
7920 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7921 Context.getCanonicalType(Context.getRecordType(Derived)));
7922 DeclarationNameInfo NameInfo(Name, UsingLoc);
7923
7924 TemplateParameterList *TemplateParams = 0;
7925 if (const FunctionTemplateDecl *FTD =
7926 BaseCtor->getDescribedFunctionTemplate()) {
7927 TemplateParams = FTD->getTemplateParameters();
7928 // We're reusing template parameters from a different DeclContext. This
7929 // is questionable at best, but works out because the template depth in
7930 // both places is guaranteed to be 0.
7931 // FIXME: Rebuild the template parameters in the new context, and
7932 // transform the function type to refer to them.
7933 }
7934
7935 // Build type source info pointing at the using-declaration. This is
7936 // required by template instantiation.
7937 TypeSourceInfo *TInfo =
7938 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
7939 FunctionProtoTypeLoc ProtoLoc =
7940 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
7941
7942 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
7943 Context, Derived, UsingLoc, NameInfo, DerivedType,
7944 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
7945 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7946
7947 // Build an unevaluated exception specification for this constructor.
7948 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
7949 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7950 EPI.ExceptionSpecType = EST_Unevaluated;
7951 EPI.ExceptionSpecDecl = DerivedCtor;
7952 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
7953 FPT->getArgTypes(), EPI));
7954
7955 // Build the parameter declarations.
7956 SmallVector<ParmVarDecl *, 16> ParamDecls;
7957 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
7958 TypeSourceInfo *TInfo =
7959 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
7960 ParmVarDecl *PD = ParmVarDecl::Create(
7961 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
7962 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
7963 PD->setScopeInfo(0, I);
7964 PD->setImplicit();
7965 ParamDecls.push_back(PD);
7966 ProtoLoc.setArg(I, PD);
7967 }
7968
7969 // Set up the new constructor.
7970 DerivedCtor->setAccess(BaseCtor->getAccess());
7971 DerivedCtor->setParams(ParamDecls);
7972 DerivedCtor->setInheritedConstructor(BaseCtor);
7973 if (BaseCtor->isDeleted())
7974 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
7975
7976 // If this is a constructor template, build the template declaration.
7977 if (TemplateParams) {
7978 FunctionTemplateDecl *DerivedTemplate =
7979 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
7980 TemplateParams, DerivedCtor);
7981 DerivedTemplate->setAccess(BaseCtor->getAccess());
7982 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
7983 Derived->addDecl(DerivedTemplate);
7984 } else {
7985 Derived->addDecl(DerivedCtor);
7986 }
7987
7988 Entry.BaseCtor = BaseCtor;
7989 Entry.DerivedCtor = DerivedCtor;
7990 }
7991
7992 Sema &SemaRef;
7993 CXXRecordDecl *Derived;
7994 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
7995 MapType Map;
7996};
7997}
7998
7999void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8000 // Defer declaring the inheriting constructors until the class is
8001 // instantiated.
8002 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008003 return;
8004
Richard Smith4841ca52013-04-10 05:48:59 +00008005 // Find base classes from which we might inherit constructors.
8006 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8007 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8008 BaseE = ClassDecl->bases_end();
8009 BaseIt != BaseE; ++BaseIt)
8010 if (BaseIt->getInheritConstructors())
8011 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008012
Richard Smith4841ca52013-04-10 05:48:59 +00008013 // Go no further if we're not inheriting any constructors.
8014 if (InheritedBases.empty())
8015 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008016
Richard Smith4841ca52013-04-10 05:48:59 +00008017 // Declare the inherited constructors.
8018 InheritingConstructorInfo ICI(*this, ClassDecl);
8019 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8020 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008021}
8022
Richard Smith07b0fdc2013-03-18 21:12:30 +00008023void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8024 CXXConstructorDecl *Constructor) {
8025 CXXRecordDecl *ClassDecl = Constructor->getParent();
8026 assert(Constructor->getInheritedConstructor() &&
8027 !Constructor->doesThisDeclarationHaveABody() &&
8028 !Constructor->isDeleted());
8029
8030 SynthesizedFunctionScope Scope(*this, Constructor);
8031 DiagnosticErrorTrap Trap(Diags);
8032 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8033 Trap.hasErrorOccurred()) {
8034 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8035 << Context.getTagDeclType(ClassDecl);
8036 Constructor->setInvalidDecl();
8037 return;
8038 }
8039
8040 SourceLocation Loc = Constructor->getLocation();
8041 Constructor->setBody(new (Context) CompoundStmt(Loc));
8042
8043 Constructor->setUsed();
8044 MarkVTableUsed(CurrentLocation, ClassDecl);
8045
8046 if (ASTMutationListener *L = getASTMutationListener()) {
8047 L->CompletedImplicitDefinition(Constructor);
8048 }
8049}
8050
8051
Sean Huntcb45a0f2011-05-12 22:46:25 +00008052Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008053Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8054 CXXRecordDecl *ClassDecl = MD->getParent();
8055
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008056 // C++ [except.spec]p14:
8057 // An implicitly declared special member function (Clause 12) shall have
8058 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008059 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008060 if (ClassDecl->isInvalidDecl())
8061 return ExceptSpec;
8062
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008063 // Direct base-class destructors.
8064 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8065 BEnd = ClassDecl->bases_end();
8066 B != BEnd; ++B) {
8067 if (B->isVirtual()) // Handled below.
8068 continue;
8069
8070 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008071 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008072 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008073 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008074
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008075 // Virtual base-class destructors.
8076 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8077 BEnd = ClassDecl->vbases_end();
8078 B != BEnd; ++B) {
8079 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008080 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008081 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008082 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008083
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008084 // Field destructors.
8085 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8086 FEnd = ClassDecl->field_end();
8087 F != FEnd; ++F) {
8088 if (const RecordType *RecordTy
8089 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008090 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008091 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008092 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008093
Sean Huntcb45a0f2011-05-12 22:46:25 +00008094 return ExceptSpec;
8095}
8096
8097CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8098 // C++ [class.dtor]p2:
8099 // If a class has no user-declared destructor, a destructor is
8100 // declared implicitly. An implicitly-declared destructor is an
8101 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008102 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008103
Richard Smithafb49182012-11-29 01:34:07 +00008104 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8105 if (DSM.isAlreadyBeingDeclared())
8106 return 0;
8107
Douglas Gregor4923aa22010-07-02 20:37:36 +00008108 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008109 CanQualType ClassType
8110 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008111 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008112 DeclarationName Name
8113 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008114 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008115 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008116 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8117 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008118 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008119 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008120 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008121 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008122
8123 // Build an exception specification pointing back at this destructor.
8124 FunctionProtoType::ExtProtoInfo EPI;
8125 EPI.ExceptionSpecType = EST_Unevaluated;
8126 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008127 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8128 ArrayRef<QualType>(),
8129 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008130
Richard Smithbc2a35d2012-12-08 08:32:28 +00008131 AddOverriddenMethods(ClassDecl, Destructor);
8132
8133 // We don't need to use SpecialMemberIsTrivial here; triviality for
8134 // destructors is easy to compute.
8135 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8136
8137 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008138 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008139
Douglas Gregor4923aa22010-07-02 20:37:36 +00008140 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008141 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008142
Douglas Gregor4923aa22010-07-02 20:37:36 +00008143 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008144 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008145 PushOnScopeChains(Destructor, S, false);
8146 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008147
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008148 return Destructor;
8149}
8150
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008151void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008152 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008153 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008154 !Destructor->doesThisDeclarationHaveABody() &&
8155 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008156 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008157 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008158 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008159
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008160 if (Destructor->isInvalidDecl())
8161 return;
8162
Eli Friedman9a14db32012-10-18 20:14:08 +00008163 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008164
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008165 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008166 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8167 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008168
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008169 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008170 Diag(CurrentLocation, diag::note_member_synthesized_at)
8171 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8172
8173 Destructor->setInvalidDecl();
8174 return;
8175 }
8176
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008177 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008178 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008179 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008180 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008181 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008182
8183 if (ASTMutationListener *L = getASTMutationListener()) {
8184 L->CompletedImplicitDefinition(Destructor);
8185 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008186}
8187
Richard Smitha4156b82012-04-21 18:42:51 +00008188/// \brief Perform any semantic analysis which needs to be delayed until all
8189/// pending class member declarations have been parsed.
8190void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008191 // If the context is an invalid C++ class, just suppress these checks.
8192 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8193 if (Record->isInvalidDecl()) {
8194 DelayedDestructorExceptionSpecChecks.clear();
8195 return;
8196 }
8197 }
8198
Richard Smitha4156b82012-04-21 18:42:51 +00008199 // Perform any deferred checking of exception specifications for virtual
8200 // destructors.
8201 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8202 i != e; ++i) {
8203 const CXXDestructorDecl *Dtor =
8204 DelayedDestructorExceptionSpecChecks[i].first;
8205 assert(!Dtor->getParent()->isDependentType() &&
8206 "Should not ever add destructors of templates into the list.");
8207 CheckOverridingFunctionExceptionSpec(Dtor,
8208 DelayedDestructorExceptionSpecChecks[i].second);
8209 }
8210 DelayedDestructorExceptionSpecChecks.clear();
8211}
8212
Richard Smithb9d0b762012-07-27 04:22:15 +00008213void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8214 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008215 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008216 "adjusting dtor exception specs was introduced in c++11");
8217
Sebastian Redl0ee33912011-05-19 05:13:44 +00008218 // C++11 [class.dtor]p3:
8219 // A declaration of a destructor that does not have an exception-
8220 // specification is implicitly considered to have the same exception-
8221 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008222 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008223 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008224 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008225 return;
8226
Chandler Carruth3f224b22011-09-20 04:55:26 +00008227 // Replace the destructor's type, building off the existing one. Fortunately,
8228 // the only thing of interest in the destructor type is its extended info.
8229 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008230 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8231 EPI.ExceptionSpecType = EST_Unevaluated;
8232 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00008233 Destructor->setType(Context.getFunctionType(Context.VoidTy,
8234 ArrayRef<QualType>(),
8235 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008236
Sebastian Redl0ee33912011-05-19 05:13:44 +00008237 // FIXME: If the destructor has a body that could throw, and the newly created
8238 // spec doesn't allow exceptions, we should emit a warning, because this
8239 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008240 // However, we don't have a body or an exception specification yet, so it
8241 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008242}
8243
Richard Smith8c889532012-11-14 00:50:40 +00008244/// When generating a defaulted copy or move assignment operator, if a field
8245/// should be copied with __builtin_memcpy rather than via explicit assignments,
8246/// do so. This optimization only applies for arrays of scalars, and for arrays
8247/// of class type where the selected copy/move-assignment operator is trivial.
8248static StmtResult
8249buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8250 Expr *To, Expr *From) {
8251 // Compute the size of the memory buffer to be copied.
8252 QualType SizeType = S.Context.getSizeType();
8253 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8254 S.Context.getTypeSizeInChars(T).getQuantity());
8255
8256 // Take the address of the field references for "from" and "to". We
8257 // directly construct UnaryOperators here because semantic analysis
8258 // does not permit us to take the address of an xvalue.
8259 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8260 S.Context.getPointerType(From->getType()),
8261 VK_RValue, OK_Ordinary, Loc);
8262 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8263 S.Context.getPointerType(To->getType()),
8264 VK_RValue, OK_Ordinary, Loc);
8265
8266 const Type *E = T->getBaseElementTypeUnsafe();
8267 bool NeedsCollectableMemCpy =
8268 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8269
8270 // Create a reference to the __builtin_objc_memmove_collectable function
8271 StringRef MemCpyName = NeedsCollectableMemCpy ?
8272 "__builtin_objc_memmove_collectable" :
8273 "__builtin_memcpy";
8274 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8275 Sema::LookupOrdinaryName);
8276 S.LookupName(R, S.TUScope, true);
8277
8278 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8279 if (!MemCpy)
8280 // Something went horribly wrong earlier, and we will have complained
8281 // about it.
8282 return StmtError();
8283
8284 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8285 VK_RValue, Loc, 0);
8286 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8287
8288 Expr *CallArgs[] = {
8289 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8290 };
8291 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8292 Loc, CallArgs, Loc);
8293
8294 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8295 return S.Owned(Call.takeAs<Stmt>());
8296}
8297
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008298/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008299/// \c To.
8300///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008301/// This routine is used to copy/move the members of a class with an
8302/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008303/// copied are arrays, this routine builds for loops to copy them.
8304///
8305/// \param S The Sema object used for type-checking.
8306///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008307/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008308///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008309/// \param T The type of the expressions being copied/moved. Both expressions
8310/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008311///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008312/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008313///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008314/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008315///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008316/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008317/// Otherwise, it's a non-static member subobject.
8318///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008319/// \param Copying Whether we're copying or moving.
8320///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008321/// \param Depth Internal parameter recording the depth of the recursion.
8322///
Richard Smith8c889532012-11-14 00:50:40 +00008323/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8324/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008325static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008326buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8327 Expr *To, Expr *From,
8328 bool CopyingBaseSubobject, bool Copying,
8329 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008330 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008331 // Each subobject is assigned in the manner appropriate to its type:
8332 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008333 // - if the subobject is of class type, as if by a call to operator= with
8334 // the subobject as the object expression and the corresponding
8335 // subobject of x as a single function argument (as if by explicit
8336 // qualification; that is, ignoring any possible virtual overriding
8337 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008338 //
8339 // C++03 [class.copy]p13:
8340 // - if the subobject is of class type, the copy assignment operator for
8341 // the class is used (as if by explicit qualification; that is,
8342 // ignoring any possible virtual overriding functions in more derived
8343 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008344 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8345 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008346
Douglas Gregor06a9f362010-05-01 20:49:11 +00008347 // Look for operator=.
8348 DeclarationName Name
8349 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8350 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8351 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008352
Richard Smith044c8aa2012-11-13 00:54:12 +00008353 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8354 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008355 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008356 LookupResult::Filter F = OpLookup.makeFilter();
8357 while (F.hasNext()) {
8358 NamedDecl *D = F.next();
8359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8360 if (Method->isCopyAssignmentOperator() ||
8361 (!Copying && Method->isMoveAssignmentOperator()))
8362 continue;
8363
8364 F.erase();
8365 }
8366 F.done();
John McCallb0207482010-03-16 06:11:48 +00008367 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008368
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008369 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008370 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008371 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008372 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008373 // ambiguities), we need to cast "this" to that subobject type; to
8374 // ensure that we don't go through the virtual call mechanism, we need
8375 // to qualify the operator= name with the base class (see below). However,
8376 // this means that if the base class has a protected copy assignment
8377 // operator, the protected member access check will fail. So, we
8378 // rewrite "protected" access to "public" access in this case, since we
8379 // know by construction that we're calling from a derived class.
8380 if (CopyingBaseSubobject) {
8381 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8382 L != LEnd; ++L) {
8383 if (L.getAccess() == AS_protected)
8384 L.setAccess(AS_public);
8385 }
8386 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008387
Douglas Gregor06a9f362010-05-01 20:49:11 +00008388 // Create the nested-name-specifier that will be used to qualify the
8389 // reference to operator=; this is required to suppress the virtual
8390 // call mechanism.
8391 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008392 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008393 SS.MakeTrivial(S.Context,
8394 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008395 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008396 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008397
Douglas Gregor06a9f362010-05-01 20:49:11 +00008398 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008399 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008400 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008401 /*TemplateKWLoc=*/SourceLocation(),
8402 /*FirstQualifierInScope=*/0,
8403 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008404 /*TemplateArgs=*/0,
8405 /*SuppressQualifierCheck=*/true);
8406 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008407 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008408
Douglas Gregor06a9f362010-05-01 20:49:11 +00008409 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008410
Richard Smith044c8aa2012-11-13 00:54:12 +00008411 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008412 OpEqualRef.takeAs<Expr>(),
8413 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008414 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008415 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008416
Richard Smith8c889532012-11-14 00:50:40 +00008417 // If we built a call to a trivial 'operator=' while copying an array,
8418 // bail out. We'll replace the whole shebang with a memcpy.
8419 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8420 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8421 return StmtResult((Stmt*)0);
8422
Richard Smith044c8aa2012-11-13 00:54:12 +00008423 // Convert to an expression-statement, and clean up any produced
8424 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008425 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008426 }
John McCallb0207482010-03-16 06:11:48 +00008427
Richard Smith044c8aa2012-11-13 00:54:12 +00008428 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008429 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008430 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008431 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008432 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008433 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008434 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008435 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008436 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008437
8438 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008439 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008440
Douglas Gregor06a9f362010-05-01 20:49:11 +00008441 // Construct a loop over the array bounds, e.g.,
8442 //
8443 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8444 //
8445 // that will copy each of the array elements.
8446 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008447
Douglas Gregor06a9f362010-05-01 20:49:11 +00008448 // Create the iteration variable.
8449 IdentifierInfo *IterationVarName = 0;
8450 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008451 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008452 llvm::raw_svector_ostream OS(Str);
8453 OS << "__i" << Depth;
8454 IterationVarName = &S.Context.Idents.get(OS.str());
8455 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008456 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008457 IterationVarName, SizeType,
8458 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008459 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008460
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461 // Initialize the iteration variable to zero.
8462 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008463 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008464
8465 // Create a reference to the iteration variable; we'll use this several
8466 // times throughout.
8467 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008468 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008469 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008470 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8471 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8472
Douglas Gregor06a9f362010-05-01 20:49:11 +00008473 // Create the DeclStmt that holds the iteration variable.
8474 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008475
Douglas Gregor06a9f362010-05-01 20:49:11 +00008476 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008477 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008478 IterationVarRefRVal,
8479 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008480 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008481 IterationVarRefRVal,
8482 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008483 if (!Copying) // Cast to rvalue
8484 From = CastForMoving(S, From);
8485
8486 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008487 StmtResult Copy =
8488 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8489 To, From, CopyingBaseSubobject,
8490 Copying, Depth + 1);
8491 // Bail out if copying fails or if we determined that we should use memcpy.
8492 if (Copy.isInvalid() || !Copy.get())
8493 return Copy;
8494
8495 // Create the comparison against the array bound.
8496 llvm::APInt Upper
8497 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8498 Expr *Comparison
8499 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8500 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8501 BO_NE, S.Context.BoolTy,
8502 VK_RValue, OK_Ordinary, Loc, false);
8503
8504 // Create the pre-increment of the iteration variable.
8505 Expr *Increment
8506 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8507 VK_LValue, OK_Ordinary, Loc);
8508
Douglas Gregor06a9f362010-05-01 20:49:11 +00008509 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008510 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008511 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008512 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008513 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008514}
8515
Richard Smith8c889532012-11-14 00:50:40 +00008516static StmtResult
8517buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8518 Expr *To, Expr *From,
8519 bool CopyingBaseSubobject, bool Copying) {
8520 // Maybe we should use a memcpy?
8521 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8522 T.isTriviallyCopyableType(S.Context))
8523 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8524
8525 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8526 CopyingBaseSubobject,
8527 Copying, 0));
8528
8529 // If we ended up picking a trivial assignment operator for an array of a
8530 // non-trivially-copyable class type, just emit a memcpy.
8531 if (!Result.isInvalid() && !Result.get())
8532 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8533
8534 return Result;
8535}
8536
Richard Smithb9d0b762012-07-27 04:22:15 +00008537Sema::ImplicitExceptionSpecification
8538Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8539 CXXRecordDecl *ClassDecl = MD->getParent();
8540
8541 ImplicitExceptionSpecification ExceptSpec(*this);
8542 if (ClassDecl->isInvalidDecl())
8543 return ExceptSpec;
8544
8545 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8546 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8547 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8548
Douglas Gregorb87786f2010-07-01 17:48:08 +00008549 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008550 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008551 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008552
8553 // It is unspecified whether or not an implicit copy assignment operator
8554 // attempts to deduplicate calls to assignment operators of virtual bases are
8555 // made. As such, this exception specification is effectively unspecified.
8556 // Based on a similar decision made for constness in C++0x, we're erring on
8557 // the side of assuming such calls to be made regardless of whether they
8558 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008559 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8560 BaseEnd = ClassDecl->bases_end();
8561 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008562 if (Base->isVirtual())
8563 continue;
8564
Douglas Gregora376d102010-07-02 21:50:04 +00008565 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008566 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008567 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8568 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008569 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008570 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008571
8572 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8573 BaseEnd = ClassDecl->vbases_end();
8574 Base != BaseEnd; ++Base) {
8575 CXXRecordDecl *BaseClassDecl
8576 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8577 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8578 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008579 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008580 }
8581
Douglas Gregorb87786f2010-07-01 17:48:08 +00008582 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8583 FieldEnd = ClassDecl->field_end();
8584 Field != FieldEnd;
8585 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008586 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008587 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8588 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008589 LookupCopyingAssignment(FieldClassDecl,
8590 ArgQuals | FieldType.getCVRQualifiers(),
8591 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008592 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008593 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008594 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008595
Richard Smithb9d0b762012-07-27 04:22:15 +00008596 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008597}
8598
8599CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8600 // Note: The following rules are largely analoguous to the copy
8601 // constructor rules. Note that virtual bases are not taken into account
8602 // for determining the argument type of the operator. Note also that
8603 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008604 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008605
Richard Smithafb49182012-11-29 01:34:07 +00008606 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8607 if (DSM.isAlreadyBeingDeclared())
8608 return 0;
8609
Sean Hunt30de05c2011-05-14 05:23:20 +00008610 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8611 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008612 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008613 ArgType = ArgType.withConst();
8614 ArgType = Context.getLValueReferenceType(ArgType);
8615
Douglas Gregord3c35902010-07-01 16:36:15 +00008616 // An implicitly-declared copy assignment operator is an inline public
8617 // member of its class.
8618 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008619 SourceLocation ClassLoc = ClassDecl->getLocation();
8620 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008621 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008622 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008623 /*TInfo=*/0,
8624 /*StorageClass=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008625 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008626 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008627 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008628 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008629 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008630
8631 // Build an exception specification pointing back at this member.
8632 FunctionProtoType::ExtProtoInfo EPI;
8633 EPI.ExceptionSpecType = EST_Unevaluated;
8634 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008635 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008636
Douglas Gregord3c35902010-07-01 16:36:15 +00008637 // Add the parameter to the operator.
8638 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008639 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008640 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008641 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008642 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008643
Richard Smithbc2a35d2012-12-08 08:32:28 +00008644 AddOverriddenMethods(ClassDecl, CopyAssignment);
8645
8646 CopyAssignment->setTrivial(
8647 ClassDecl->needsOverloadResolutionForCopyAssignment()
8648 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8649 : ClassDecl->hasTrivialCopyAssignment());
8650
Nico Weberafcc96a2012-01-23 03:19:29 +00008651 // C++0x [class.copy]p19:
8652 // .... If the class definition does not explicitly declare a copy
8653 // assignment operator, there is no user-declared move constructor, and
8654 // there is no user-declared move assignment operator, a copy assignment
8655 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008656 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008657 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008658
Richard Smithbc2a35d2012-12-08 08:32:28 +00008659 // Note that we have added this copy-assignment operator.
8660 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8661
8662 if (Scope *S = getScopeForContext(ClassDecl))
8663 PushOnScopeChains(CopyAssignment, S, false);
8664 ClassDecl->addDecl(CopyAssignment);
8665
Douglas Gregord3c35902010-07-01 16:36:15 +00008666 return CopyAssignment;
8667}
8668
Douglas Gregor06a9f362010-05-01 20:49:11 +00008669void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8670 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008671 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008672 CopyAssignOperator->isOverloadedOperator() &&
8673 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008674 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8675 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008676 "DefineImplicitCopyAssignment called for wrong function");
8677
8678 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8679
8680 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8681 CopyAssignOperator->setInvalidDecl();
8682 return;
8683 }
8684
8685 CopyAssignOperator->setUsed();
8686
Eli Friedman9a14db32012-10-18 20:14:08 +00008687 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008688 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008689
8690 // C++0x [class.copy]p30:
8691 // The implicitly-defined or explicitly-defaulted copy assignment operator
8692 // for a non-union class X performs memberwise copy assignment of its
8693 // subobjects. The direct base classes of X are assigned first, in the
8694 // order of their declaration in the base-specifier-list, and then the
8695 // immediate non-static data members of X are assigned, in the order in
8696 // which they were declared in the class definition.
8697
8698 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008699 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008700
8701 // The parameter for the "other" object, which we are copying from.
8702 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8703 Qualifiers OtherQuals = Other->getType().getQualifiers();
8704 QualType OtherRefType = Other->getType();
8705 if (const LValueReferenceType *OtherRef
8706 = OtherRefType->getAs<LValueReferenceType>()) {
8707 OtherRefType = OtherRef->getPointeeType();
8708 OtherQuals = OtherRefType.getQualifiers();
8709 }
8710
8711 // Our location for everything implicitly-generated.
8712 SourceLocation Loc = CopyAssignOperator->getLocation();
8713
8714 // Construct a reference to the "other" object. We'll be using this
8715 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008716 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008717 assert(OtherRef && "Reference to parameter cannot fail!");
8718
8719 // Construct the "this" pointer. We'll be using this throughout the generated
8720 // ASTs.
8721 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8722 assert(This && "Reference to this cannot fail!");
8723
8724 // Assign base classes.
8725 bool Invalid = false;
8726 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8727 E = ClassDecl->bases_end(); Base != E; ++Base) {
8728 // Form the assignment:
8729 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8730 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008731 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008732 Invalid = true;
8733 continue;
8734 }
8735
John McCallf871d0c2010-08-07 06:22:56 +00008736 CXXCastPath BasePath;
8737 BasePath.push_back(Base);
8738
Douglas Gregor06a9f362010-05-01 20:49:11 +00008739 // Construct the "from" expression, which is an implicit cast to the
8740 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008741 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008742 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8743 CK_UncheckedDerivedToBase,
8744 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008745
8746 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008747 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008748
8749 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008750 To = ImpCastExprToType(To.take(),
8751 Context.getCVRQualifiedType(BaseType,
8752 CopyAssignOperator->getTypeQualifiers()),
8753 CK_UncheckedDerivedToBase,
8754 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008755
8756 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008757 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008758 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008759 /*CopyingBaseSubobject=*/true,
8760 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008761 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008762 Diag(CurrentLocation, diag::note_member_synthesized_at)
8763 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8764 CopyAssignOperator->setInvalidDecl();
8765 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008766 }
8767
8768 // Success! Record the copy.
8769 Statements.push_back(Copy.takeAs<Expr>());
8770 }
8771
Douglas Gregor06a9f362010-05-01 20:49:11 +00008772 // Assign non-static members.
8773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8774 FieldEnd = ClassDecl->field_end();
8775 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008776 if (Field->isUnnamedBitfield())
8777 continue;
8778
Douglas Gregor06a9f362010-05-01 20:49:11 +00008779 // Check for members of reference type; we can't copy those.
8780 if (Field->getType()->isReferenceType()) {
8781 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8782 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8783 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008784 Diag(CurrentLocation, diag::note_member_synthesized_at)
8785 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008786 Invalid = true;
8787 continue;
8788 }
8789
8790 // Check for members of const-qualified, non-class type.
8791 QualType BaseType = Context.getBaseElementType(Field->getType());
8792 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8793 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8794 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8795 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008796 Diag(CurrentLocation, diag::note_member_synthesized_at)
8797 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008798 Invalid = true;
8799 continue;
8800 }
John McCallb77115d2011-06-17 00:18:42 +00008801
8802 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008803 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8804 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008805
8806 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008807 if (FieldType->isIncompleteArrayType()) {
8808 assert(ClassDecl->hasFlexibleArrayMember() &&
8809 "Incomplete array type is not valid");
8810 continue;
8811 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008812
8813 // Build references to the field in the object we're copying from and to.
8814 CXXScopeSpec SS; // Intentionally empty
8815 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8816 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008817 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008818 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008819 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008820 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008821 SS, SourceLocation(), 0,
8822 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008823 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008824 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008825 SS, SourceLocation(), 0,
8826 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008827 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8828 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008829
Douglas Gregor06a9f362010-05-01 20:49:11 +00008830 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008831 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008832 To.get(), From.get(),
8833 /*CopyingBaseSubobject=*/false,
8834 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008835 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008836 Diag(CurrentLocation, diag::note_member_synthesized_at)
8837 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8838 CopyAssignOperator->setInvalidDecl();
8839 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008840 }
8841
8842 // Success! Record the copy.
8843 Statements.push_back(Copy.takeAs<Stmt>());
8844 }
8845
8846 if (!Invalid) {
8847 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008848 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008849
John McCall60d7b3a2010-08-24 06:29:42 +00008850 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008851 if (Return.isInvalid())
8852 Invalid = true;
8853 else {
8854 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008855
8856 if (Trap.hasErrorOccurred()) {
8857 Diag(CurrentLocation, diag::note_member_synthesized_at)
8858 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8859 Invalid = true;
8860 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008861 }
8862 }
8863
8864 if (Invalid) {
8865 CopyAssignOperator->setInvalidDecl();
8866 return;
8867 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008868
8869 StmtResult Body;
8870 {
8871 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008872 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008873 /*isStmtExpr=*/false);
8874 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8875 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008876 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008877
8878 if (ASTMutationListener *L = getASTMutationListener()) {
8879 L->CompletedImplicitDefinition(CopyAssignOperator);
8880 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008881}
8882
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008883Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008884Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8885 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886
Richard Smithb9d0b762012-07-27 04:22:15 +00008887 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008888 if (ClassDecl->isInvalidDecl())
8889 return ExceptSpec;
8890
8891 // C++0x [except.spec]p14:
8892 // An implicitly declared special member function (Clause 12) shall have an
8893 // exception-specification. [...]
8894
8895 // It is unspecified whether or not an implicit move assignment operator
8896 // attempts to deduplicate calls to assignment operators of virtual bases are
8897 // made. As such, this exception specification is effectively unspecified.
8898 // Based on a similar decision made for constness in C++0x, we're erring on
8899 // the side of assuming such calls to be made regardless of whether they
8900 // actually happen.
8901 // Note that a move constructor is not implicitly declared when there are
8902 // virtual bases, but it can still be user-declared and explicitly defaulted.
8903 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8904 BaseEnd = ClassDecl->bases_end();
8905 Base != BaseEnd; ++Base) {
8906 if (Base->isVirtual())
8907 continue;
8908
8909 CXXRecordDecl *BaseClassDecl
8910 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8911 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008912 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008913 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008914 }
8915
8916 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8917 BaseEnd = ClassDecl->vbases_end();
8918 Base != BaseEnd; ++Base) {
8919 CXXRecordDecl *BaseClassDecl
8920 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8921 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008922 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008923 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008924 }
8925
8926 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8927 FieldEnd = ClassDecl->field_end();
8928 Field != FieldEnd;
8929 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008930 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008931 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008932 if (CXXMethodDecl *MoveAssign =
8933 LookupMovingAssignment(FieldClassDecl,
8934 FieldType.getCVRQualifiers(),
8935 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008936 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008937 }
8938 }
8939
8940 return ExceptSpec;
8941}
8942
Richard Smith1c931be2012-04-02 18:40:40 +00008943/// Determine whether the class type has any direct or indirect virtual base
8944/// classes which have a non-trivial move assignment operator.
8945static bool
8946hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8947 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8948 BaseEnd = ClassDecl->vbases_end();
8949 Base != BaseEnd; ++Base) {
8950 CXXRecordDecl *BaseClass =
8951 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8952
8953 // Try to declare the move assignment. If it would be deleted, then the
8954 // class does not have a non-trivial move assignment.
8955 if (BaseClass->needsImplicitMoveAssignment())
8956 S.DeclareImplicitMoveAssignment(BaseClass);
8957
Richard Smith426391c2012-11-16 00:53:38 +00008958 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008959 return true;
8960 }
8961
8962 return false;
8963}
8964
8965/// Determine whether the given type either has a move constructor or is
8966/// trivially copyable.
8967static bool
8968hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8969 Type = S.Context.getBaseElementType(Type);
8970
8971 // FIXME: Technically, non-trivially-copyable non-class types, such as
8972 // reference types, are supposed to return false here, but that appears
8973 // to be a standard defect.
8974 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008975 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008976 return true;
8977
8978 if (Type.isTriviallyCopyableType(S.Context))
8979 return true;
8980
8981 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008982 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8983 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008984 if (ClassDecl->needsImplicitMoveConstructor())
8985 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008986 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008987 }
8988
Richard Smithe5411b72012-12-01 02:35:44 +00008989 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8990 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008991 if (ClassDecl->needsImplicitMoveAssignment())
8992 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008993 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008994}
8995
8996/// Determine whether all non-static data members and direct or virtual bases
8997/// of class \p ClassDecl have either a move operation, or are trivially
8998/// copyable.
8999static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9000 bool IsConstructor) {
9001 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9002 BaseEnd = ClassDecl->bases_end();
9003 Base != BaseEnd; ++Base) {
9004 if (Base->isVirtual())
9005 continue;
9006
9007 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9008 return false;
9009 }
9010
9011 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9012 BaseEnd = ClassDecl->vbases_end();
9013 Base != BaseEnd; ++Base) {
9014 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9015 return false;
9016 }
9017
9018 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9019 FieldEnd = ClassDecl->field_end();
9020 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009021 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009022 return false;
9023 }
9024
9025 return true;
9026}
9027
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009028CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009029 // C++11 [class.copy]p20:
9030 // If the definition of a class X does not explicitly declare a move
9031 // assignment operator, one will be implicitly declared as defaulted
9032 // if and only if:
9033 //
9034 // - [first 4 bullets]
9035 assert(ClassDecl->needsImplicitMoveAssignment());
9036
Richard Smithafb49182012-11-29 01:34:07 +00009037 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9038 if (DSM.isAlreadyBeingDeclared())
9039 return 0;
9040
Richard Smith1c931be2012-04-02 18:40:40 +00009041 // [Checked after we build the declaration]
9042 // - the move assignment operator would not be implicitly defined as
9043 // deleted,
9044
9045 // [DR1402]:
9046 // - X has no direct or indirect virtual base class with a non-trivial
9047 // move assignment operator, and
9048 // - each of X's non-static data members and direct or virtual base classes
9049 // has a type that either has a move assignment operator or is trivially
9050 // copyable.
9051 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9052 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9053 ClassDecl->setFailedImplicitMoveAssignment();
9054 return 0;
9055 }
9056
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009057 // Note: The following rules are largely analoguous to the move
9058 // constructor rules.
9059
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009060 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9061 QualType RetType = Context.getLValueReferenceType(ArgType);
9062 ArgType = Context.getRValueReferenceType(ArgType);
9063
9064 // An implicitly-declared move assignment operator is an inline public
9065 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009066 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9067 SourceLocation ClassLoc = ClassDecl->getLocation();
9068 DeclarationNameInfo NameInfo(Name, ClassLoc);
9069 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00009070 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009071 /*TInfo=*/0,
9072 /*StorageClass=*/SC_None,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009073 /*isInline=*/true,
9074 /*isConstexpr=*/false,
9075 SourceLocation());
9076 MoveAssignment->setAccess(AS_public);
9077 MoveAssignment->setDefaulted();
9078 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009079
Richard Smithb9d0b762012-07-27 04:22:15 +00009080 // Build an exception specification pointing back at this member.
9081 FunctionProtoType::ExtProtoInfo EPI;
9082 EPI.ExceptionSpecType = EST_Unevaluated;
9083 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009084 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009085
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009086 // Add the parameter to the operator.
9087 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9088 ClassLoc, ClassLoc, /*Id=*/0,
9089 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009090 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009091 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009092
Richard Smithbc2a35d2012-12-08 08:32:28 +00009093 AddOverriddenMethods(ClassDecl, MoveAssignment);
9094
9095 MoveAssignment->setTrivial(
9096 ClassDecl->needsOverloadResolutionForMoveAssignment()
9097 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9098 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009099
9100 // C++0x [class.copy]p9:
9101 // If the definition of a class X does not explicitly declare a move
9102 // assignment operator, one will be implicitly declared as defaulted if and
9103 // only if:
9104 // [...]
9105 // - the move assignment operator would not be implicitly defined as
9106 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009107 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009108 // Cache this result so that we don't try to generate this over and over
9109 // on every lookup, leaking memory and wasting time.
9110 ClassDecl->setFailedImplicitMoveAssignment();
9111 return 0;
9112 }
9113
Richard Smithbc2a35d2012-12-08 08:32:28 +00009114 // Note that we have added this copy-assignment operator.
9115 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9116
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009117 if (Scope *S = getScopeForContext(ClassDecl))
9118 PushOnScopeChains(MoveAssignment, S, false);
9119 ClassDecl->addDecl(MoveAssignment);
9120
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009121 return MoveAssignment;
9122}
9123
9124void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9125 CXXMethodDecl *MoveAssignOperator) {
9126 assert((MoveAssignOperator->isDefaulted() &&
9127 MoveAssignOperator->isOverloadedOperator() &&
9128 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009129 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9130 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009131 "DefineImplicitMoveAssignment called for wrong function");
9132
9133 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9134
9135 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9136 MoveAssignOperator->setInvalidDecl();
9137 return;
9138 }
9139
9140 MoveAssignOperator->setUsed();
9141
Eli Friedman9a14db32012-10-18 20:14:08 +00009142 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009143 DiagnosticErrorTrap Trap(Diags);
9144
9145 // C++0x [class.copy]p28:
9146 // The implicitly-defined or move assignment operator for a non-union class
9147 // X performs memberwise move assignment of its subobjects. The direct base
9148 // classes of X are assigned first, in the order of their declaration in the
9149 // base-specifier-list, and then the immediate non-static data members of X
9150 // are assigned, in the order in which they were declared in the class
9151 // definition.
9152
9153 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009154 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009155
9156 // The parameter for the "other" object, which we are move from.
9157 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9158 QualType OtherRefType = Other->getType()->
9159 getAs<RValueReferenceType>()->getPointeeType();
9160 assert(OtherRefType.getQualifiers() == 0 &&
9161 "Bad argument type of defaulted move assignment");
9162
9163 // Our location for everything implicitly-generated.
9164 SourceLocation Loc = MoveAssignOperator->getLocation();
9165
9166 // Construct a reference to the "other" object. We'll be using this
9167 // throughout the generated ASTs.
9168 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9169 assert(OtherRef && "Reference to parameter cannot fail!");
9170 // Cast to rvalue.
9171 OtherRef = CastForMoving(*this, OtherRef);
9172
9173 // Construct the "this" pointer. We'll be using this throughout the generated
9174 // ASTs.
9175 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9176 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009177
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009178 // Assign base classes.
9179 bool Invalid = false;
9180 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9181 E = ClassDecl->bases_end(); Base != E; ++Base) {
9182 // Form the assignment:
9183 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9184 QualType BaseType = Base->getType().getUnqualifiedType();
9185 if (!BaseType->isRecordType()) {
9186 Invalid = true;
9187 continue;
9188 }
9189
9190 CXXCastPath BasePath;
9191 BasePath.push_back(Base);
9192
9193 // Construct the "from" expression, which is an implicit cast to the
9194 // appropriately-qualified base type.
9195 Expr *From = OtherRef;
9196 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009197 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009198
9199 // Dereference "this".
9200 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9201
9202 // Implicitly cast "this" to the appropriately-qualified base type.
9203 To = ImpCastExprToType(To.take(),
9204 Context.getCVRQualifiedType(BaseType,
9205 MoveAssignOperator->getTypeQualifiers()),
9206 CK_UncheckedDerivedToBase,
9207 VK_LValue, &BasePath);
9208
9209 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009210 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009211 To.get(), From,
9212 /*CopyingBaseSubobject=*/true,
9213 /*Copying=*/false);
9214 if (Move.isInvalid()) {
9215 Diag(CurrentLocation, diag::note_member_synthesized_at)
9216 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9217 MoveAssignOperator->setInvalidDecl();
9218 return;
9219 }
9220
9221 // Success! Record the move.
9222 Statements.push_back(Move.takeAs<Expr>());
9223 }
9224
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009225 // Assign non-static members.
9226 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9227 FieldEnd = ClassDecl->field_end();
9228 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009229 if (Field->isUnnamedBitfield())
9230 continue;
9231
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009232 // Check for members of reference type; we can't move those.
9233 if (Field->getType()->isReferenceType()) {
9234 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9235 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9236 Diag(Field->getLocation(), diag::note_declared_at);
9237 Diag(CurrentLocation, diag::note_member_synthesized_at)
9238 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9239 Invalid = true;
9240 continue;
9241 }
9242
9243 // Check for members of const-qualified, non-class type.
9244 QualType BaseType = Context.getBaseElementType(Field->getType());
9245 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9246 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9247 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9248 Diag(Field->getLocation(), diag::note_declared_at);
9249 Diag(CurrentLocation, diag::note_member_synthesized_at)
9250 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9251 Invalid = true;
9252 continue;
9253 }
9254
9255 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009256 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9257 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009258
9259 QualType FieldType = Field->getType().getNonReferenceType();
9260 if (FieldType->isIncompleteArrayType()) {
9261 assert(ClassDecl->hasFlexibleArrayMember() &&
9262 "Incomplete array type is not valid");
9263 continue;
9264 }
9265
9266 // Build references to the field in the object we're copying from and to.
9267 CXXScopeSpec SS; // Intentionally empty
9268 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9269 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009270 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009271 MemberLookup.resolveKind();
9272 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9273 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009274 SS, SourceLocation(), 0,
9275 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009276 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9277 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009278 SS, SourceLocation(), 0,
9279 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009280 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9281 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9282
9283 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9284 "Member reference with rvalue base must be rvalue except for reference "
9285 "members, which aren't allowed for move assignment.");
9286
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009287 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009288 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009289 To.get(), From.get(),
9290 /*CopyingBaseSubobject=*/false,
9291 /*Copying=*/false);
9292 if (Move.isInvalid()) {
9293 Diag(CurrentLocation, diag::note_member_synthesized_at)
9294 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9295 MoveAssignOperator->setInvalidDecl();
9296 return;
9297 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009298
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009299 // Success! Record the copy.
9300 Statements.push_back(Move.takeAs<Stmt>());
9301 }
9302
9303 if (!Invalid) {
9304 // Add a "return *this;"
9305 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9306
9307 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9308 if (Return.isInvalid())
9309 Invalid = true;
9310 else {
9311 Statements.push_back(Return.takeAs<Stmt>());
9312
9313 if (Trap.hasErrorOccurred()) {
9314 Diag(CurrentLocation, diag::note_member_synthesized_at)
9315 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9316 Invalid = true;
9317 }
9318 }
9319 }
9320
9321 if (Invalid) {
9322 MoveAssignOperator->setInvalidDecl();
9323 return;
9324 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009325
9326 StmtResult Body;
9327 {
9328 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009329 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009330 /*isStmtExpr=*/false);
9331 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9332 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009333 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9334
9335 if (ASTMutationListener *L = getASTMutationListener()) {
9336 L->CompletedImplicitDefinition(MoveAssignOperator);
9337 }
9338}
9339
Richard Smithb9d0b762012-07-27 04:22:15 +00009340Sema::ImplicitExceptionSpecification
9341Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9342 CXXRecordDecl *ClassDecl = MD->getParent();
9343
9344 ImplicitExceptionSpecification ExceptSpec(*this);
9345 if (ClassDecl->isInvalidDecl())
9346 return ExceptSpec;
9347
9348 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9349 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9350 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9351
Douglas Gregor0d405db2010-07-01 20:59:04 +00009352 // C++ [except.spec]p14:
9353 // An implicitly declared special member function (Clause 12) shall have an
9354 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009355 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9356 BaseEnd = ClassDecl->bases_end();
9357 Base != BaseEnd;
9358 ++Base) {
9359 // Virtual bases are handled below.
9360 if (Base->isVirtual())
9361 continue;
9362
Douglas Gregor22584312010-07-02 23:41:54 +00009363 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009364 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009365 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009366 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009367 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009368 }
9369 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9370 BaseEnd = ClassDecl->vbases_end();
9371 Base != BaseEnd;
9372 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009373 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009374 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009375 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009376 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009377 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009378 }
9379 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9380 FieldEnd = ClassDecl->field_end();
9381 Field != FieldEnd;
9382 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009383 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009384 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9385 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009386 LookupCopyingConstructor(FieldClassDecl,
9387 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009388 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009389 }
9390 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009391
Richard Smithb9d0b762012-07-27 04:22:15 +00009392 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009393}
9394
9395CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9396 CXXRecordDecl *ClassDecl) {
9397 // C++ [class.copy]p4:
9398 // If the class definition does not explicitly declare a copy
9399 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009400 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009401
Richard Smithafb49182012-11-29 01:34:07 +00009402 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9403 if (DSM.isAlreadyBeingDeclared())
9404 return 0;
9405
Sean Hunt49634cf2011-05-13 06:10:58 +00009406 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9407 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009408 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009409 if (Const)
9410 ArgType = ArgType.withConst();
9411 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009412
Richard Smith7756afa2012-06-10 05:43:50 +00009413 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9414 CXXCopyConstructor,
9415 Const);
9416
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009417 DeclarationName Name
9418 = Context.DeclarationNames.getCXXConstructorName(
9419 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009420 SourceLocation ClassLoc = ClassDecl->getLocation();
9421 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009422
9423 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009424 // member of its class.
9425 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009426 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009427 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009428 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009429 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009430 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009431
Richard Smithb9d0b762012-07-27 04:22:15 +00009432 // Build an exception specification pointing back at this member.
9433 FunctionProtoType::ExtProtoInfo EPI;
9434 EPI.ExceptionSpecType = EST_Unevaluated;
9435 EPI.ExceptionSpecDecl = CopyConstructor;
9436 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009437 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009438
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009439 // Add the parameter to the constructor.
9440 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009441 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009442 /*IdentifierInfo=*/0,
9443 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009444 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009445 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009446
Richard Smithbc2a35d2012-12-08 08:32:28 +00009447 CopyConstructor->setTrivial(
9448 ClassDecl->needsOverloadResolutionForCopyConstructor()
9449 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9450 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009451
Nico Weberafcc96a2012-01-23 03:19:29 +00009452 // C++11 [class.copy]p8:
9453 // ... If the class definition does not explicitly declare a copy
9454 // constructor, there is no user-declared move constructor, and there is no
9455 // user-declared move assignment operator, a copy constructor is implicitly
9456 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009457 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009458 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009459
Richard Smithbc2a35d2012-12-08 08:32:28 +00009460 // Note that we have declared this constructor.
9461 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9462
9463 if (Scope *S = getScopeForContext(ClassDecl))
9464 PushOnScopeChains(CopyConstructor, S, false);
9465 ClassDecl->addDecl(CopyConstructor);
9466
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009467 return CopyConstructor;
9468}
9469
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009470void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009471 CXXConstructorDecl *CopyConstructor) {
9472 assert((CopyConstructor->isDefaulted() &&
9473 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009474 !CopyConstructor->doesThisDeclarationHaveABody() &&
9475 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009476 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009477
Anders Carlsson63010a72010-04-23 16:24:12 +00009478 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009479 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009480
Eli Friedman9a14db32012-10-18 20:14:08 +00009481 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009482 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009483
David Blaikie93c86172013-01-17 05:26:25 +00009484 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009485 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009486 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009487 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009488 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009489 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009490 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009491 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9492 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009493 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009494 /*isStmtExpr=*/false)
9495 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009496 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009497 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009498
9499 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009500 if (ASTMutationListener *L = getASTMutationListener()) {
9501 L->CompletedImplicitDefinition(CopyConstructor);
9502 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009503}
9504
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009505Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009506Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9507 CXXRecordDecl *ClassDecl = MD->getParent();
9508
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009509 // C++ [except.spec]p14:
9510 // An implicitly declared special member function (Clause 12) shall have an
9511 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009512 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009513 if (ClassDecl->isInvalidDecl())
9514 return ExceptSpec;
9515
9516 // Direct base-class constructors.
9517 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9518 BEnd = ClassDecl->bases_end();
9519 B != BEnd; ++B) {
9520 if (B->isVirtual()) // Handled below.
9521 continue;
9522
9523 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9524 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009525 CXXConstructorDecl *Constructor =
9526 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009527 // If this is a deleted function, add it anyway. This might be conformant
9528 // with the standard. This might not. I'm not sure. It might not matter.
9529 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009530 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009531 }
9532 }
9533
9534 // Virtual base-class constructors.
9535 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9536 BEnd = ClassDecl->vbases_end();
9537 B != BEnd; ++B) {
9538 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9539 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009540 CXXConstructorDecl *Constructor =
9541 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009542 // If this is a deleted function, add it anyway. This might be conformant
9543 // with the standard. This might not. I'm not sure. It might not matter.
9544 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009545 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009546 }
9547 }
9548
9549 // Field constructors.
9550 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9551 FEnd = ClassDecl->field_end();
9552 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009553 QualType FieldType = Context.getBaseElementType(F->getType());
9554 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9555 CXXConstructorDecl *Constructor =
9556 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009557 // If this is a deleted function, add it anyway. This might be conformant
9558 // with the standard. This might not. I'm not sure. It might not matter.
9559 // In particular, the problem is that this function never gets called. It
9560 // might just be ill-formed because this function attempts to refer to
9561 // a deleted function here.
9562 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009563 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009564 }
9565 }
9566
9567 return ExceptSpec;
9568}
9569
9570CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9571 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009572 // C++11 [class.copy]p9:
9573 // If the definition of a class X does not explicitly declare a move
9574 // constructor, one will be implicitly declared as defaulted if and only if:
9575 //
9576 // - [first 4 bullets]
9577 assert(ClassDecl->needsImplicitMoveConstructor());
9578
Richard Smithafb49182012-11-29 01:34:07 +00009579 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9580 if (DSM.isAlreadyBeingDeclared())
9581 return 0;
9582
Richard Smith1c931be2012-04-02 18:40:40 +00009583 // [Checked after we build the declaration]
9584 // - the move assignment operator would not be implicitly defined as
9585 // deleted,
9586
9587 // [DR1402]:
9588 // - each of X's non-static data members and direct or virtual base classes
9589 // has a type that either has a move constructor or is trivially copyable.
9590 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9591 ClassDecl->setFailedImplicitMoveConstructor();
9592 return 0;
9593 }
9594
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009595 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9596 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009597
Richard Smith7756afa2012-06-10 05:43:50 +00009598 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9599 CXXMoveConstructor,
9600 false);
9601
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009602 DeclarationName Name
9603 = Context.DeclarationNames.getCXXConstructorName(
9604 Context.getCanonicalType(ClassType));
9605 SourceLocation ClassLoc = ClassDecl->getLocation();
9606 DeclarationNameInfo NameInfo(Name, ClassLoc);
9607
9608 // C++0x [class.copy]p11:
9609 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009610 // member of its class.
9611 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009612 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009613 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009614 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009615 MoveConstructor->setAccess(AS_public);
9616 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009617
Richard Smithb9d0b762012-07-27 04:22:15 +00009618 // Build an exception specification pointing back at this member.
9619 FunctionProtoType::ExtProtoInfo EPI;
9620 EPI.ExceptionSpecType = EST_Unevaluated;
9621 EPI.ExceptionSpecDecl = MoveConstructor;
9622 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009623 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009624
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009625 // Add the parameter to the constructor.
9626 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9627 ClassLoc, ClassLoc,
9628 /*IdentifierInfo=*/0,
9629 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009630 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009631 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009632
Richard Smithbc2a35d2012-12-08 08:32:28 +00009633 MoveConstructor->setTrivial(
9634 ClassDecl->needsOverloadResolutionForMoveConstructor()
9635 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9636 : ClassDecl->hasTrivialMoveConstructor());
9637
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009638 // C++0x [class.copy]p9:
9639 // If the definition of a class X does not explicitly declare a move
9640 // constructor, one will be implicitly declared as defaulted if and only if:
9641 // [...]
9642 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009643 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009644 // Cache this result so that we don't try to generate this over and over
9645 // on every lookup, leaking memory and wasting time.
9646 ClassDecl->setFailedImplicitMoveConstructor();
9647 return 0;
9648 }
9649
9650 // Note that we have declared this constructor.
9651 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9652
9653 if (Scope *S = getScopeForContext(ClassDecl))
9654 PushOnScopeChains(MoveConstructor, S, false);
9655 ClassDecl->addDecl(MoveConstructor);
9656
9657 return MoveConstructor;
9658}
9659
9660void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9661 CXXConstructorDecl *MoveConstructor) {
9662 assert((MoveConstructor->isDefaulted() &&
9663 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009664 !MoveConstructor->doesThisDeclarationHaveABody() &&
9665 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009666 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9667
9668 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9669 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9670
Eli Friedman9a14db32012-10-18 20:14:08 +00009671 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009672 DiagnosticErrorTrap Trap(Diags);
9673
David Blaikie93c86172013-01-17 05:26:25 +00009674 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009675 Trap.hasErrorOccurred()) {
9676 Diag(CurrentLocation, diag::note_member_synthesized_at)
9677 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9678 MoveConstructor->setInvalidDecl();
9679 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009680 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009681 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9682 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009683 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009684 /*isStmtExpr=*/false)
9685 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009686 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009687 }
9688
9689 MoveConstructor->setUsed();
9690
9691 if (ASTMutationListener *L = getASTMutationListener()) {
9692 L->CompletedImplicitDefinition(MoveConstructor);
9693 }
9694}
9695
Douglas Gregore4e68d42012-02-15 19:33:52 +00009696bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9697 return FD->isDeleted() &&
9698 (FD->isDefaulted() || FD->isImplicit()) &&
9699 isa<CXXMethodDecl>(FD);
9700}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009701
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009702/// \brief Mark the call operator of the given lambda closure type as "used".
9703static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9704 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009705 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009706 Lambda->lookup(
9707 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009708 CallOperator->setReferenced();
9709 CallOperator->setUsed();
9710}
9711
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009712void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9713 SourceLocation CurrentLocation,
9714 CXXConversionDecl *Conv)
9715{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009716 CXXRecordDecl *Lambda = Conv->getParent();
9717
9718 // Make sure that the lambda call operator is marked used.
9719 markLambdaCallOperatorUsed(*this, Lambda);
9720
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009721 Conv->setUsed();
9722
Eli Friedman9a14db32012-10-18 20:14:08 +00009723 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009724 DiagnosticErrorTrap Trap(Diags);
9725
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009726 // Return the address of the __invoke function.
9727 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9728 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009729 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009730 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9731 VK_LValue, Conv->getLocation()).take();
9732 assert(FunctionRef && "Can't refer to __invoke function?");
9733 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009734 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009735 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009736 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009737
9738 // Fill in the __invoke function with a dummy implementation. IR generation
9739 // will fill in the actual details.
9740 Invoke->setUsed();
9741 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009742 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009743
9744 if (ASTMutationListener *L = getASTMutationListener()) {
9745 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009746 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009747 }
9748}
9749
9750void Sema::DefineImplicitLambdaToBlockPointerConversion(
9751 SourceLocation CurrentLocation,
9752 CXXConversionDecl *Conv)
9753{
9754 Conv->setUsed();
9755
Eli Friedman9a14db32012-10-18 20:14:08 +00009756 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009757 DiagnosticErrorTrap Trap(Diags);
9758
Douglas Gregorac1303e2012-02-22 05:02:47 +00009759 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009760 Expr *This = ActOnCXXThis(CurrentLocation).take();
9761 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009762
Eli Friedman23f02672012-03-01 04:01:32 +00009763 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9764 Conv->getLocation(),
9765 Conv, DerefThis);
9766
9767 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9768 // behavior. Note that only the general conversion function does this
9769 // (since it's unusable otherwise); in the case where we inline the
9770 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009771 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009772 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9773 CK_CopyAndAutoreleaseBlockObject,
9774 BuildBlock.get(), 0, VK_RValue);
9775
9776 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009777 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009778 Conv->setInvalidDecl();
9779 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009780 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009781
Douglas Gregorac1303e2012-02-22 05:02:47 +00009782 // Create the return statement that returns the block from the conversion
9783 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009784 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009785 if (Return.isInvalid()) {
9786 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9787 Conv->setInvalidDecl();
9788 return;
9789 }
9790
9791 // Set the body of the conversion function.
9792 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009793 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009794 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009795 Conv->getLocation()));
9796
Douglas Gregorac1303e2012-02-22 05:02:47 +00009797 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009798 if (ASTMutationListener *L = getASTMutationListener()) {
9799 L->CompletedImplicitDefinition(Conv);
9800 }
9801}
9802
Douglas Gregorf52757d2012-03-10 06:53:13 +00009803/// \brief Determine whether the given list arguments contains exactly one
9804/// "real" (non-default) argument.
9805static bool hasOneRealArgument(MultiExprArg Args) {
9806 switch (Args.size()) {
9807 case 0:
9808 return false;
9809
9810 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009811 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009812 return false;
9813
9814 // fall through
9815 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009816 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009817 }
9818
9819 return false;
9820}
9821
John McCall60d7b3a2010-08-24 06:29:42 +00009822ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009823Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009824 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009825 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009826 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009827 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009828 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009829 unsigned ConstructKind,
9830 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009831 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009832
Douglas Gregor2f599792010-04-02 18:24:57 +00009833 // C++0x [class.copy]p34:
9834 // When certain criteria are met, an implementation is allowed to
9835 // omit the copy/move construction of a class object, even if the
9836 // copy/move constructor and/or destructor for the object have
9837 // side effects. [...]
9838 // - when a temporary class object that has not been bound to a
9839 // reference (12.2) would be copied/moved to a class object
9840 // with the same cv-unqualified type, the copy/move operation
9841 // can be omitted by constructing the temporary object
9842 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009843 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009844 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009845 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009846 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009847 }
Mike Stump1eb44332009-09-09 15:08:12 +00009848
9849 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009850 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009851 IsListInitialization, RequiresZeroInit,
9852 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009853}
9854
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009855/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9856/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009857ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009858Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9859 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009860 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009861 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009862 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009863 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009864 unsigned ConstructKind,
9865 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009866 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009867 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009868 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009869 HadMultipleCandidates,
9870 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009871 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9872 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009873}
9874
John McCall68c6c9a2010-02-02 09:10:11 +00009875void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009876 if (VD->isInvalidDecl()) return;
9877
John McCall68c6c9a2010-02-02 09:10:11 +00009878 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009879 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009880 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009881 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009882
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009883 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009884 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009885 CheckDestructorAccess(VD->getLocation(), Destructor,
9886 PDiag(diag::err_access_dtor_var)
9887 << VD->getDeclName()
9888 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009889 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009890
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009891 if (!VD->hasGlobalStorage()) return;
9892
9893 // Emit warning for non-trivial dtor in global scope (a real global,
9894 // class-static, function-static).
9895 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9896
9897 // TODO: this should be re-enabled for static locals by !CXAAtExit
9898 if (!VD->isStaticLocal())
9899 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009900}
9901
Douglas Gregor39da0b82009-09-09 23:08:42 +00009902/// \brief Given a constructor and the set of arguments provided for the
9903/// constructor, convert the arguments and add any required default arguments
9904/// to form a proper call to this constructor.
9905///
9906/// \returns true if an error occurred, false otherwise.
9907bool
9908Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9909 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009910 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009911 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009912 bool AllowExplicit,
9913 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009914 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9915 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009916 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009917
9918 const FunctionProtoType *Proto
9919 = Constructor->getType()->getAs<FunctionProtoType>();
9920 assert(Proto && "Constructor without a prototype?");
9921 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009922
9923 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009924 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009925 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009926 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009927 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009928
9929 VariadicCallType CallType =
9930 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009931 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009932 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9933 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009934 CallType, AllowExplicit,
9935 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009936 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009937
9938 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9939
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009940 CheckConstructorCall(Constructor,
9941 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9942 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009943 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009944
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009945 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009946}
9947
Anders Carlsson20d45d22009-12-12 00:32:00 +00009948static inline bool
9949CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9950 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009951 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009952 if (isa<NamespaceDecl>(DC)) {
9953 return SemaRef.Diag(FnDecl->getLocation(),
9954 diag::err_operator_new_delete_declared_in_namespace)
9955 << FnDecl->getDeclName();
9956 }
9957
9958 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009959 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009960 return SemaRef.Diag(FnDecl->getLocation(),
9961 diag::err_operator_new_delete_declared_static)
9962 << FnDecl->getDeclName();
9963 }
9964
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009965 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009966}
9967
Anders Carlsson156c78e2009-12-13 17:53:43 +00009968static inline bool
9969CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9970 CanQualType ExpectedResultType,
9971 CanQualType ExpectedFirstParamType,
9972 unsigned DependentParamTypeDiag,
9973 unsigned InvalidParamTypeDiag) {
9974 QualType ResultType =
9975 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9976
9977 // Check that the result type is not dependent.
9978 if (ResultType->isDependentType())
9979 return SemaRef.Diag(FnDecl->getLocation(),
9980 diag::err_operator_new_delete_dependent_result_type)
9981 << FnDecl->getDeclName() << ExpectedResultType;
9982
9983 // Check that the result type is what we expect.
9984 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9985 return SemaRef.Diag(FnDecl->getLocation(),
9986 diag::err_operator_new_delete_invalid_result_type)
9987 << FnDecl->getDeclName() << ExpectedResultType;
9988
9989 // A function template must have at least 2 parameters.
9990 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9991 return SemaRef.Diag(FnDecl->getLocation(),
9992 diag::err_operator_new_delete_template_too_few_parameters)
9993 << FnDecl->getDeclName();
9994
9995 // The function decl must have at least 1 parameter.
9996 if (FnDecl->getNumParams() == 0)
9997 return SemaRef.Diag(FnDecl->getLocation(),
9998 diag::err_operator_new_delete_too_few_parameters)
9999 << FnDecl->getDeclName();
10000
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010001 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010002 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10003 if (FirstParamType->isDependentType())
10004 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10005 << FnDecl->getDeclName() << ExpectedFirstParamType;
10006
10007 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010008 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010009 ExpectedFirstParamType)
10010 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10011 << FnDecl->getDeclName() << ExpectedFirstParamType;
10012
10013 return false;
10014}
10015
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010016static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010017CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010018 // C++ [basic.stc.dynamic.allocation]p1:
10019 // A program is ill-formed if an allocation function is declared in a
10020 // namespace scope other than global scope or declared static in global
10021 // scope.
10022 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10023 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010024
10025 CanQualType SizeTy =
10026 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10027
10028 // C++ [basic.stc.dynamic.allocation]p1:
10029 // The return type shall be void*. The first parameter shall have type
10030 // std::size_t.
10031 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10032 SizeTy,
10033 diag::err_operator_new_dependent_param_type,
10034 diag::err_operator_new_param_type))
10035 return true;
10036
10037 // C++ [basic.stc.dynamic.allocation]p1:
10038 // The first parameter shall not have an associated default argument.
10039 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010040 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010041 diag::err_operator_new_default_arg)
10042 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10043
10044 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010045}
10046
10047static bool
Richard Smith444d3842012-10-20 08:26:51 +000010048CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010049 // C++ [basic.stc.dynamic.deallocation]p1:
10050 // A program is ill-formed if deallocation functions are declared in a
10051 // namespace scope other than global scope or declared static in global
10052 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010053 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10054 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010055
10056 // C++ [basic.stc.dynamic.deallocation]p2:
10057 // Each deallocation function shall return void and its first parameter
10058 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010059 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10060 SemaRef.Context.VoidPtrTy,
10061 diag::err_operator_delete_dependent_param_type,
10062 diag::err_operator_delete_param_type))
10063 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010064
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010065 return false;
10066}
10067
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010068/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10069/// of this overloaded operator is well-formed. If so, returns false;
10070/// otherwise, emits appropriate diagnostics and returns true.
10071bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010072 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010073 "Expected an overloaded operator declaration");
10074
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010075 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10076
Mike Stump1eb44332009-09-09 15:08:12 +000010077 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010078 // The allocation and deallocation functions, operator new,
10079 // operator new[], operator delete and operator delete[], are
10080 // described completely in 3.7.3. The attributes and restrictions
10081 // found in the rest of this subclause do not apply to them unless
10082 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010083 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010084 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010085
Anders Carlssona3ccda52009-12-12 00:26:23 +000010086 if (Op == OO_New || Op == OO_Array_New)
10087 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010088
10089 // C++ [over.oper]p6:
10090 // An operator function shall either be a non-static member
10091 // function or be a non-member function and have at least one
10092 // parameter whose type is a class, a reference to a class, an
10093 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010094 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10095 if (MethodDecl->isStatic())
10096 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010097 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010098 } else {
10099 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010100 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10101 ParamEnd = FnDecl->param_end();
10102 Param != ParamEnd; ++Param) {
10103 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010104 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10105 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010106 ClassOrEnumParam = true;
10107 break;
10108 }
10109 }
10110
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010111 if (!ClassOrEnumParam)
10112 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010113 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010114 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010115 }
10116
10117 // C++ [over.oper]p8:
10118 // An operator function cannot have default arguments (8.3.6),
10119 // except where explicitly stated below.
10120 //
Mike Stump1eb44332009-09-09 15:08:12 +000010121 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010122 // (C++ [over.call]p1).
10123 if (Op != OO_Call) {
10124 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10125 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010126 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010127 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010128 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010129 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010130 }
10131 }
10132
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010133 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10134 { false, false, false }
10135#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10136 , { Unary, Binary, MemberOnly }
10137#include "clang/Basic/OperatorKinds.def"
10138 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010139
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010140 bool CanBeUnaryOperator = OperatorUses[Op][0];
10141 bool CanBeBinaryOperator = OperatorUses[Op][1];
10142 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010143
10144 // C++ [over.oper]p8:
10145 // [...] Operator functions cannot have more or fewer parameters
10146 // than the number required for the corresponding operator, as
10147 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010148 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010149 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010150 if (Op != OO_Call &&
10151 ((NumParams == 1 && !CanBeUnaryOperator) ||
10152 (NumParams == 2 && !CanBeBinaryOperator) ||
10153 (NumParams < 1) || (NumParams > 2))) {
10154 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010155 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010156 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010157 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010158 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010159 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010160 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010161 assert(CanBeBinaryOperator &&
10162 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010163 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010164 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010165
Chris Lattner416e46f2008-11-21 07:57:12 +000010166 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010167 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010168 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010169
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010170 // Overloaded operators other than operator() cannot be variadic.
10171 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010172 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010173 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010174 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010175 }
10176
10177 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010178 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10179 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010180 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010181 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010182 }
10183
10184 // C++ [over.inc]p1:
10185 // The user-defined function called operator++ implements the
10186 // prefix and postfix ++ operator. If this function is a member
10187 // function with no parameters, or a non-member function with one
10188 // parameter of class or enumeration type, it defines the prefix
10189 // increment operator ++ for objects of that type. If the function
10190 // is a member function with one parameter (which shall be of type
10191 // int) or a non-member function with two parameters (the second
10192 // of which shall be of type int), it defines the postfix
10193 // increment operator ++ for objects of that type.
10194 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10195 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10196 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010197 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010198 ParamIsInt = BT->getKind() == BuiltinType::Int;
10199
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010200 if (!ParamIsInt)
10201 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010202 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010203 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010204 }
10205
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010206 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010207}
Chris Lattner5a003a42008-12-17 07:09:26 +000010208
Sean Hunta6c058d2010-01-13 09:01:02 +000010209/// CheckLiteralOperatorDeclaration - Check whether the declaration
10210/// of this literal operator function is well-formed. If so, returns
10211/// false; otherwise, emits appropriate diagnostics and returns true.
10212bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010213 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010214 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10215 << FnDecl->getDeclName();
10216 return true;
10217 }
10218
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010219 if (FnDecl->isExternC()) {
10220 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10221 return true;
10222 }
10223
Sean Hunta6c058d2010-01-13 09:01:02 +000010224 bool Valid = false;
10225
Richard Smith36f5cfe2012-03-09 08:00:36 +000010226 // This might be the definition of a literal operator template.
10227 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10228 // This might be a specialization of a literal operator template.
10229 if (!TpDecl)
10230 TpDecl = FnDecl->getPrimaryTemplate();
10231
Sean Hunt216c2782010-04-07 23:11:06 +000010232 // template <char...> type operator "" name() is the only valid template
10233 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010234 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010235 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010236 // Must have only one template parameter
10237 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10238 if (Params->size() == 1) {
10239 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010240 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010241
Sean Hunt216c2782010-04-07 23:11:06 +000010242 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010243 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10244 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10245 Valid = true;
10246 }
10247 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010248 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010249 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010250 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10251
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010252 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010253
Sean Hunt30019c02010-04-07 22:57:35 +000010254 // unsigned long long int, long double, and any character type are allowed
10255 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010256 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10257 Context.hasSameType(T, Context.LongDoubleTy) ||
10258 Context.hasSameType(T, Context.CharTy) ||
10259 Context.hasSameType(T, Context.WCharTy) ||
10260 Context.hasSameType(T, Context.Char16Ty) ||
10261 Context.hasSameType(T, Context.Char32Ty)) {
10262 if (++Param == FnDecl->param_end())
10263 Valid = true;
10264 goto FinishedParams;
10265 }
10266
Sean Hunt30019c02010-04-07 22:57:35 +000010267 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010268 const PointerType *PT = T->getAs<PointerType>();
10269 if (!PT)
10270 goto FinishedParams;
10271 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010272 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010273 goto FinishedParams;
10274 T = T.getUnqualifiedType();
10275
10276 // Move on to the second parameter;
10277 ++Param;
10278
10279 // If there is no second parameter, the first must be a const char *
10280 if (Param == FnDecl->param_end()) {
10281 if (Context.hasSameType(T, Context.CharTy))
10282 Valid = true;
10283 goto FinishedParams;
10284 }
10285
10286 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10287 // are allowed as the first parameter to a two-parameter function
10288 if (!(Context.hasSameType(T, Context.CharTy) ||
10289 Context.hasSameType(T, Context.WCharTy) ||
10290 Context.hasSameType(T, Context.Char16Ty) ||
10291 Context.hasSameType(T, Context.Char32Ty)))
10292 goto FinishedParams;
10293
10294 // The second and final parameter must be an std::size_t
10295 T = (*Param)->getType().getUnqualifiedType();
10296 if (Context.hasSameType(T, Context.getSizeType()) &&
10297 ++Param == FnDecl->param_end())
10298 Valid = true;
10299 }
10300
10301 // FIXME: This diagnostic is absolutely terrible.
10302FinishedParams:
10303 if (!Valid) {
10304 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10305 << FnDecl->getDeclName();
10306 return true;
10307 }
10308
Richard Smitha9e88b22012-03-09 08:16:22 +000010309 // A parameter-declaration-clause containing a default argument is not
10310 // equivalent to any of the permitted forms.
10311 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10312 ParamEnd = FnDecl->param_end();
10313 Param != ParamEnd; ++Param) {
10314 if ((*Param)->hasDefaultArg()) {
10315 Diag((*Param)->getDefaultArgRange().getBegin(),
10316 diag::err_literal_operator_default_argument)
10317 << (*Param)->getDefaultArgRange();
10318 break;
10319 }
10320 }
10321
Richard Smith2fb4ae32012-03-08 02:39:21 +000010322 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010323 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10324 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010325 // C++11 [usrlit.suffix]p1:
10326 // Literal suffix identifiers that do not start with an underscore
10327 // are reserved for future standardization.
10328 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010329 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010330
Sean Hunta6c058d2010-01-13 09:01:02 +000010331 return false;
10332}
10333
Douglas Gregor074149e2009-01-05 19:45:36 +000010334/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10335/// linkage specification, including the language and (if present)
10336/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10337/// the location of the language string literal, which is provided
10338/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10339/// the '{' brace. Otherwise, this linkage specification does not
10340/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010341Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10342 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010343 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010344 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010345 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010346 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010347 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010348 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010349 Language = LinkageSpecDecl::lang_cxx;
10350 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010351 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010352 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010353 }
Mike Stump1eb44332009-09-09 15:08:12 +000010354
Chris Lattnercc98eac2008-12-17 07:13:27 +000010355 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010356
Douglas Gregor074149e2009-01-05 19:45:36 +000010357 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010358 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010359 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010360 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010361 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010362}
10363
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010364/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010365/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10366/// valid, it's the position of the closing '}' brace in a linkage
10367/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010368Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010369 Decl *LinkageSpec,
10370 SourceLocation RBraceLoc) {
10371 if (LinkageSpec) {
10372 if (RBraceLoc.isValid()) {
10373 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10374 LSDecl->setRBraceLoc(RBraceLoc);
10375 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010376 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010377 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010378 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010379}
10380
Michael Han684aa732013-02-22 17:15:32 +000010381Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10382 AttributeList *AttrList,
10383 SourceLocation SemiLoc) {
10384 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10385 // Attribute declarations appertain to empty declaration so we handle
10386 // them here.
10387 if (AttrList)
10388 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010389
Michael Han684aa732013-02-22 17:15:32 +000010390 CurContext->addDecl(ED);
10391 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010392}
10393
Douglas Gregord308e622009-05-18 20:51:54 +000010394/// \brief Perform semantic analysis for the variable declaration that
10395/// occurs within a C++ catch clause, returning the newly-created
10396/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010397VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010398 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010399 SourceLocation StartLoc,
10400 SourceLocation Loc,
10401 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010402 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010403 QualType ExDeclType = TInfo->getType();
10404
Sebastian Redl4b07b292008-12-22 19:15:10 +000010405 // Arrays and functions decay.
10406 if (ExDeclType->isArrayType())
10407 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10408 else if (ExDeclType->isFunctionType())
10409 ExDeclType = Context.getPointerType(ExDeclType);
10410
10411 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10412 // The exception-declaration shall not denote a pointer or reference to an
10413 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010414 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010415 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010416 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010417 Invalid = true;
10418 }
Douglas Gregord308e622009-05-18 20:51:54 +000010419
Sebastian Redl4b07b292008-12-22 19:15:10 +000010420 QualType BaseType = ExDeclType;
10421 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010422 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010423 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010424 BaseType = Ptr->getPointeeType();
10425 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010426 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010427 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010428 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010429 BaseType = Ref->getPointeeType();
10430 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010431 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010432 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010433 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010434 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010435 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010436
Mike Stump1eb44332009-09-09 15:08:12 +000010437 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010438 RequireNonAbstractType(Loc, ExDeclType,
10439 diag::err_abstract_type_in_decl,
10440 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010441 Invalid = true;
10442
John McCall5a180392010-07-24 00:37:23 +000010443 // Only the non-fragile NeXT runtime currently supports C++ catches
10444 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010445 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010446 QualType T = ExDeclType;
10447 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10448 T = RT->getPointeeType();
10449
10450 if (T->isObjCObjectType()) {
10451 Diag(Loc, diag::err_objc_object_catch);
10452 Invalid = true;
10453 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010454 // FIXME: should this be a test for macosx-fragile specifically?
10455 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010456 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010457 }
10458 }
10459
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010460 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010461 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010462 ExDecl->setExceptionVariable(true);
10463
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010464 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010465 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010466 Invalid = true;
10467
Douglas Gregorc41b8782011-07-06 18:14:43 +000010468 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010469 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010470 // Insulate this from anything else we might currently be parsing.
10471 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10472
Douglas Gregor6d182892010-03-05 23:38:39 +000010473 // C++ [except.handle]p16:
10474 // The object declared in an exception-declaration or, if the
10475 // exception-declaration does not specify a name, a temporary (12.2) is
10476 // copy-initialized (8.5) from the exception object. [...]
10477 // The object is destroyed when the handler exits, after the destruction
10478 // of any automatic objects initialized within the handler.
10479 //
10480 // We just pretend to initialize the object with itself, then make sure
10481 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010482 QualType initType = ExDeclType;
10483
10484 InitializedEntity entity =
10485 InitializedEntity::InitializeVariable(ExDecl);
10486 InitializationKind initKind =
10487 InitializationKind::CreateCopy(Loc, SourceLocation());
10488
10489 Expr *opaqueValue =
10490 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10491 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10492 ExprResult result = sequence.Perform(*this, entity, initKind,
10493 MultiExprArg(&opaqueValue, 1));
10494 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010495 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010496 else {
10497 // If the constructor used was non-trivial, set this as the
10498 // "initializer".
10499 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10500 if (!construct->getConstructor()->isTrivial()) {
10501 Expr *init = MaybeCreateExprWithCleanups(construct);
10502 ExDecl->setInit(init);
10503 }
10504
10505 // And make sure it's destructable.
10506 FinalizeVarWithDestructor(ExDecl, recordType);
10507 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010508 }
10509 }
10510
Douglas Gregord308e622009-05-18 20:51:54 +000010511 if (Invalid)
10512 ExDecl->setInvalidDecl();
10513
10514 return ExDecl;
10515}
10516
10517/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10518/// handler.
John McCalld226f652010-08-21 09:40:31 +000010519Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010520 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010521 bool Invalid = D.isInvalidType();
10522
10523 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010524 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10525 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010526 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10527 D.getIdentifierLoc());
10528 Invalid = true;
10529 }
10530
Sebastian Redl4b07b292008-12-22 19:15:10 +000010531 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010532 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010533 LookupOrdinaryName,
10534 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010535 // The scope should be freshly made just for us. There is just no way
10536 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010537 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010538 if (PrevDecl->isTemplateParameter()) {
10539 // Maybe we will complain about the shadowed template parameter.
10540 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010541 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010542 }
10543 }
10544
Chris Lattnereaaebc72009-04-25 08:06:05 +000010545 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010546 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10547 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010548 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010549 }
10550
Douglas Gregor83cb9422010-09-09 17:09:21 +000010551 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010552 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010553 D.getIdentifierLoc(),
10554 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010555 if (Invalid)
10556 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010557
Sebastian Redl4b07b292008-12-22 19:15:10 +000010558 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010559 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010560 PushOnScopeChains(ExDecl, S);
10561 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010562 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010563
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010564 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010565 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010566}
Anders Carlssonfb311762009-03-14 00:25:26 +000010567
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010568Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010569 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010570 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010571 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010572 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010573
Richard Smithe3f470a2012-07-11 22:37:56 +000010574 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10575 return 0;
10576
10577 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10578 AssertMessage, RParenLoc, false);
10579}
10580
10581Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10582 Expr *AssertExpr,
10583 StringLiteral *AssertMessage,
10584 SourceLocation RParenLoc,
10585 bool Failed) {
10586 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10587 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010588 // In a static_assert-declaration, the constant-expression shall be a
10589 // constant expression that can be contextually converted to bool.
10590 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10591 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010592 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010593
Richard Smithdaaefc52011-12-14 23:32:26 +000010594 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010595 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010596 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010597 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010598 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010599
Richard Smithe3f470a2012-07-11 22:37:56 +000010600 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010601 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010602 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010603 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010604 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010605 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010606 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010607 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010608 }
Mike Stump1eb44332009-09-09 15:08:12 +000010609
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010610 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010611 AssertExpr, AssertMessage, RParenLoc,
10612 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010613
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010614 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010615 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010616}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010617
Douglas Gregor1d869352010-04-07 16:53:43 +000010618/// \brief Perform semantic analysis of the given friend type declaration.
10619///
10620/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010621FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010622 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010623 TypeSourceInfo *TSInfo) {
10624 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10625
10626 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010627 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010628
Richard Smith6b130222011-10-18 21:39:00 +000010629 // C++03 [class.friend]p2:
10630 // An elaborated-type-specifier shall be used in a friend declaration
10631 // for a class.*
10632 //
10633 // * The class-key of the elaborated-type-specifier is required.
10634 if (!ActiveTemplateInstantiations.empty()) {
10635 // Do not complain about the form of friend template types during
10636 // template instantiation; we will already have complained when the
10637 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010638 } else {
10639 if (!T->isElaboratedTypeSpecifier()) {
10640 // If we evaluated the type to a record type, suggest putting
10641 // a tag in front.
10642 if (const RecordType *RT = T->getAs<RecordType>()) {
10643 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010644
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010645 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010646
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010647 Diag(TypeRange.getBegin(),
10648 getLangOpts().CPlusPlus11 ?
10649 diag::warn_cxx98_compat_unelaborated_friend_type :
10650 diag::ext_unelaborated_friend_type)
10651 << (unsigned) RD->getTagKind()
10652 << T
10653 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10654 InsertionText);
10655 } else {
10656 Diag(FriendLoc,
10657 getLangOpts().CPlusPlus11 ?
10658 diag::warn_cxx98_compat_nonclass_type_friend :
10659 diag::ext_nonclass_type_friend)
10660 << T
10661 << TypeRange;
10662 }
10663 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010664 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010665 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010666 diag::warn_cxx98_compat_enum_friend :
10667 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010668 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010669 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010670 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010671
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010672 // C++11 [class.friend]p3:
10673 // A friend declaration that does not declare a function shall have one
10674 // of the following forms:
10675 // friend elaborated-type-specifier ;
10676 // friend simple-type-specifier ;
10677 // friend typename-specifier ;
10678 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10679 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10680 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010681
Douglas Gregor06245bf2010-04-07 17:57:12 +000010682 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010683 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010684 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010685 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010686}
10687
John McCall9a34edb2010-10-19 01:40:49 +000010688/// Handle a friend tag declaration where the scope specifier was
10689/// templated.
10690Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10691 unsigned TagSpec, SourceLocation TagLoc,
10692 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010693 IdentifierInfo *Name,
10694 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010695 AttributeList *Attr,
10696 MultiTemplateParamsArg TempParamLists) {
10697 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10698
10699 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010700 bool Invalid = false;
10701
10702 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010703 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010704 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010705 TempParamLists.size(),
10706 /*friend*/ true,
10707 isExplicitSpecialization,
10708 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010709 if (TemplateParams->size() > 0) {
10710 // This is a declaration of a class template.
10711 if (Invalid)
10712 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010713
Eric Christopher4110e132011-07-21 05:34:24 +000010714 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10715 SS, Name, NameLoc, Attr,
10716 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010717 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010718 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010719 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010720 } else {
10721 // The "template<>" header is extraneous.
10722 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10723 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10724 isExplicitSpecialization = true;
10725 }
10726 }
10727
10728 if (Invalid) return 0;
10729
John McCall9a34edb2010-10-19 01:40:49 +000010730 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010731 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010732 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010733 isAllExplicitSpecializations = false;
10734 break;
10735 }
10736 }
10737
10738 // FIXME: don't ignore attributes.
10739
10740 // If it's explicit specializations all the way down, just forget
10741 // about the template header and build an appropriate non-templated
10742 // friend. TODO: for source fidelity, remember the headers.
10743 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010744 if (SS.isEmpty()) {
10745 bool Owned = false;
10746 bool IsDependent = false;
10747 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10748 Attr, AS_public,
10749 /*ModulePrivateLoc=*/SourceLocation(),
10750 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010751 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010752 /*ScopedEnumUsesClassTag=*/false,
10753 /*UnderlyingType=*/TypeResult());
10754 }
10755
Douglas Gregor2494dd02011-03-01 01:34:45 +000010756 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010757 ElaboratedTypeKeyword Keyword
10758 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010759 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010760 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010761 if (T.isNull())
10762 return 0;
10763
10764 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10765 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010766 DependentNameTypeLoc TL =
10767 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010768 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010769 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010770 TL.setNameLoc(NameLoc);
10771 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010772 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010773 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010774 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010775 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010776 }
10777
10778 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010779 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010780 Friend->setAccess(AS_public);
10781 CurContext->addDecl(Friend);
10782 return Friend;
10783 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010784
10785 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10786
10787
John McCall9a34edb2010-10-19 01:40:49 +000010788
10789 // Handle the case of a templated-scope friend class. e.g.
10790 // template <class T> class A<T>::B;
10791 // FIXME: we don't support these right now.
10792 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10793 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10794 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010795 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010796 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010797 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010798 TL.setNameLoc(NameLoc);
10799
10800 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010801 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010802 Friend->setAccess(AS_public);
10803 Friend->setUnsupportedFriend(true);
10804 CurContext->addDecl(Friend);
10805 return Friend;
10806}
10807
10808
John McCalldd4a3b02009-09-16 22:47:08 +000010809/// Handle a friend type declaration. This works in tandem with
10810/// ActOnTag.
10811///
10812/// Notes on friend class templates:
10813///
10814/// We generally treat friend class declarations as if they were
10815/// declaring a class. So, for example, the elaborated type specifier
10816/// in a friend declaration is required to obey the restrictions of a
10817/// class-head (i.e. no typedefs in the scope chain), template
10818/// parameters are required to match up with simple template-ids, &c.
10819/// However, unlike when declaring a template specialization, it's
10820/// okay to refer to a template specialization without an empty
10821/// template parameter declaration, e.g.
10822/// friend class A<T>::B<unsigned>;
10823/// We permit this as a special case; if there are any template
10824/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010825/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010826Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010827 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010828 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010829
10830 assert(DS.isFriendSpecified());
10831 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10832
John McCalldd4a3b02009-09-16 22:47:08 +000010833 // Try to convert the decl specifier to a type. This works for
10834 // friend templates because ActOnTag never produces a ClassTemplateDecl
10835 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010836 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010837 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10838 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010839 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010840 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010841
Douglas Gregor6ccab972010-12-16 01:14:37 +000010842 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10843 return 0;
10844
John McCalldd4a3b02009-09-16 22:47:08 +000010845 // This is definitely an error in C++98. It's probably meant to
10846 // be forbidden in C++0x, too, but the specification is just
10847 // poorly written.
10848 //
10849 // The problem is with declarations like the following:
10850 // template <T> friend A<T>::foo;
10851 // where deciding whether a class C is a friend or not now hinges
10852 // on whether there exists an instantiation of A that causes
10853 // 'foo' to equal C. There are restrictions on class-heads
10854 // (which we declare (by fiat) elaborated friend declarations to
10855 // be) that makes this tractable.
10856 //
10857 // FIXME: handle "template <> friend class A<T>;", which
10858 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010859 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010860 Diag(Loc, diag::err_tagless_friend_type_template)
10861 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010862 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010863 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010864
John McCall02cace72009-08-28 07:59:38 +000010865 // C++98 [class.friend]p1: A friend of a class is a function
10866 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010867 // This is fixed in DR77, which just barely didn't make the C++03
10868 // deadline. It's also a very silly restriction that seriously
10869 // affects inner classes and which nobody else seems to implement;
10870 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010871 //
10872 // But note that we could warn about it: it's always useless to
10873 // friend one of your own members (it's not, however, worthless to
10874 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010875
John McCalldd4a3b02009-09-16 22:47:08 +000010876 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010877 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010878 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010879 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010880 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010881 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010882 DS.getFriendSpecLoc());
10883 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010884 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010885
10886 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010887 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010888
John McCalldd4a3b02009-09-16 22:47:08 +000010889 D->setAccess(AS_public);
10890 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010891
John McCalld226f652010-08-21 09:40:31 +000010892 return D;
John McCall02cace72009-08-28 07:59:38 +000010893}
10894
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010895NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10896 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010897 const DeclSpec &DS = D.getDeclSpec();
10898
10899 assert(DS.isFriendSpecified());
10900 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10901
10902 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010903 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010904
10905 // C++ [class.friend]p1
10906 // A friend of a class is a function or class....
10907 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010908 // It *doesn't* see through dependent types, which is correct
10909 // according to [temp.arg.type]p3:
10910 // If a declaration acquires a function type through a
10911 // type dependent on a template-parameter and this causes
10912 // a declaration that does not use the syntactic form of a
10913 // function declarator to have a function type, the program
10914 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010915 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010916 Diag(Loc, diag::err_unexpected_friend);
10917
10918 // It might be worthwhile to try to recover by creating an
10919 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010920 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010921 }
10922
10923 // C++ [namespace.memdef]p3
10924 // - If a friend declaration in a non-local class first declares a
10925 // class or function, the friend class or function is a member
10926 // of the innermost enclosing namespace.
10927 // - The name of the friend is not found by simple name lookup
10928 // until a matching declaration is provided in that namespace
10929 // scope (either before or after the class declaration granting
10930 // friendship).
10931 // - If a friend function is called, its name may be found by the
10932 // name lookup that considers functions from namespaces and
10933 // classes associated with the types of the function arguments.
10934 // - When looking for a prior declaration of a class or a function
10935 // declared as a friend, scopes outside the innermost enclosing
10936 // namespace scope are not considered.
10937
John McCall337ec3d2010-10-12 23:13:28 +000010938 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010939 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10940 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010941 assert(Name);
10942
Douglas Gregor6ccab972010-12-16 01:14:37 +000010943 // Check for unexpanded parameter packs.
10944 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10945 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10946 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10947 return 0;
10948
John McCall67d1a672009-08-06 02:15:43 +000010949 // The context we found the declaration in, or in which we should
10950 // create the declaration.
10951 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010952 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010953 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010954 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010955
John McCall337ec3d2010-10-12 23:13:28 +000010956 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010957
John McCall337ec3d2010-10-12 23:13:28 +000010958 // There are four cases here.
10959 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010960 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010961 // there as appropriate.
10962 // Recover from invalid scope qualifiers as if they just weren't there.
10963 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010964 // C++0x [namespace.memdef]p3:
10965 // If the name in a friend declaration is neither qualified nor
10966 // a template-id and the declaration is a function or an
10967 // elaborated-type-specifier, the lookup to determine whether
10968 // the entity has been previously declared shall not consider
10969 // any scopes outside the innermost enclosing namespace.
10970 // C++0x [class.friend]p11:
10971 // If a friend declaration appears in a local class and the name
10972 // specified is an unqualified name, a prior declaration is
10973 // looked up without considering scopes that are outside the
10974 // innermost enclosing non-class scope. For a friend function
10975 // declaration, if there is no prior declaration, the program is
10976 // ill-formed.
10977 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010978 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010979
John McCall29ae6e52010-10-13 05:45:15 +000010980 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010981 DC = CurContext;
10982 while (true) {
10983 // Skip class contexts. If someone can cite chapter and verse
10984 // for this behavior, that would be nice --- it's what GCC and
10985 // EDG do, and it seems like a reasonable intent, but the spec
10986 // really only says that checks for unqualified existing
10987 // declarations should stop at the nearest enclosing namespace,
10988 // not that they should only consider the nearest enclosing
10989 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010990 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010991 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010992
John McCall68263142009-11-18 22:49:29 +000010993 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010994
10995 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010996 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010997 break;
John McCall29ae6e52010-10-13 05:45:15 +000010998
John McCall8a407372010-10-14 22:22:28 +000010999 if (isTemplateId) {
11000 if (isa<TranslationUnitDecl>(DC)) break;
11001 } else {
11002 if (DC->isFileContext()) break;
11003 }
John McCall67d1a672009-08-06 02:15:43 +000011004 DC = DC->getParent();
11005 }
11006
John McCall380aaa42010-10-13 06:22:15 +000011007 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011008
Douglas Gregor883af832011-10-10 01:11:59 +000011009 // C++ [class.friend]p6:
11010 // A function can be defined in a friend declaration of a class if and
11011 // only if the class is a non-local class (9.8), the function name is
11012 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011013 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011014 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11015 }
11016
John McCall337ec3d2010-10-12 23:13:28 +000011017 // - There's a non-dependent scope specifier, in which case we
11018 // compute it and do a previous lookup there for a function
11019 // or function template.
11020 } else if (!SS.getScopeRep()->isDependent()) {
11021 DC = computeDeclContext(SS);
11022 if (!DC) return 0;
11023
11024 if (RequireCompleteDeclContext(SS, DC)) return 0;
11025
11026 LookupQualifiedName(Previous, DC);
11027
11028 // Ignore things found implicitly in the wrong scope.
11029 // TODO: better diagnostics for this case. Suggesting the right
11030 // qualified scope would be nice...
11031 LookupResult::Filter F = Previous.makeFilter();
11032 while (F.hasNext()) {
11033 NamedDecl *D = F.next();
11034 if (!DC->InEnclosingNamespaceSetOf(
11035 D->getDeclContext()->getRedeclContext()))
11036 F.erase();
11037 }
11038 F.done();
11039
11040 if (Previous.empty()) {
11041 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011042 Diag(Loc, diag::err_qualified_friend_not_found)
11043 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011044 return 0;
11045 }
11046
11047 // C++ [class.friend]p1: A friend of a class is a function or
11048 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011049 if (DC->Equals(CurContext))
11050 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011051 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011052 diag::warn_cxx98_compat_friend_is_member :
11053 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011054
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011055 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011056 // C++ [class.friend]p6:
11057 // A function can be defined in a friend declaration of a class if and
11058 // only if the class is a non-local class (9.8), the function name is
11059 // unqualified, and the function has namespace scope.
11060 SemaDiagnosticBuilder DB
11061 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11062
11063 DB << SS.getScopeRep();
11064 if (DC->isFileContext())
11065 DB << FixItHint::CreateRemoval(SS.getRange());
11066 SS.clear();
11067 }
John McCall337ec3d2010-10-12 23:13:28 +000011068
11069 // - There's a scope specifier that does not match any template
11070 // parameter lists, in which case we use some arbitrary context,
11071 // create a method or method template, and wait for instantiation.
11072 // - There's a scope specifier that does match some template
11073 // parameter lists, which we don't handle right now.
11074 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011075 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011076 // C++ [class.friend]p6:
11077 // A function can be defined in a friend declaration of a class if and
11078 // only if the class is a non-local class (9.8), the function name is
11079 // unqualified, and the function has namespace scope.
11080 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11081 << SS.getScopeRep();
11082 }
11083
John McCall337ec3d2010-10-12 23:13:28 +000011084 DC = CurContext;
11085 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011086 }
Douglas Gregor883af832011-10-10 01:11:59 +000011087
John McCall29ae6e52010-10-13 05:45:15 +000011088 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011089 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011090 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11091 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11092 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011093 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011094 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11095 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011096 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011097 }
John McCall67d1a672009-08-06 02:15:43 +000011098 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011099
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011100 // FIXME: This is an egregious hack to cope with cases where the scope stack
11101 // does not contain the declaration context, i.e., in an out-of-line
11102 // definition of a class.
11103 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11104 if (!DCScope) {
11105 FakeDCScope.setEntity(DC);
11106 DCScope = &FakeDCScope;
11107 }
11108
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011109 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011110 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011111 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011112 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011113
Douglas Gregor182ddf02009-09-28 00:08:27 +000011114 assert(ND->getDeclContext() == DC);
11115 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011116
John McCallab88d972009-08-31 22:39:49 +000011117 // Add the function declaration to the appropriate lookup tables,
11118 // adjusting the redeclarations list as necessary. We don't
11119 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011120 //
John McCallab88d972009-08-31 22:39:49 +000011121 // Also update the scope-based lookup if the target context's
11122 // lookup context is in lexical scope.
11123 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011124 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011125 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011126 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011127 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011128 }
John McCall02cace72009-08-28 07:59:38 +000011129
11130 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011131 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011132 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011133 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011134 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011135
John McCall1f2e1a92012-08-10 03:15:35 +000011136 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011137 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011138 } else {
11139 if (DC->isRecord()) CheckFriendAccess(ND);
11140
John McCall6102ca12010-10-16 06:59:13 +000011141 FunctionDecl *FD;
11142 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11143 FD = FTD->getTemplatedDecl();
11144 else
11145 FD = cast<FunctionDecl>(ND);
11146
11147 // Mark templated-scope function declarations as unsupported.
11148 if (FD->getNumTemplateParameterLists())
11149 FrD->setUnsupportedFriend(true);
11150 }
John McCall337ec3d2010-10-12 23:13:28 +000011151
John McCalld226f652010-08-21 09:40:31 +000011152 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011153}
11154
John McCalld226f652010-08-21 09:40:31 +000011155void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11156 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011157
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011158 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011159 if (!Fn) {
11160 Diag(DelLoc, diag::err_deleted_non_function);
11161 return;
11162 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011163
Douglas Gregoref96ee02012-01-14 16:38:05 +000011164 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011165 // Don't consider the implicit declaration we generate for explicit
11166 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011167 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11168 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011169 Diag(DelLoc, diag::err_deleted_decl_not_first);
11170 Diag(Prev->getLocation(), diag::note_previous_declaration);
11171 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011172 // If the declaration wasn't the first, we delete the function anyway for
11173 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011174 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011175 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011176
11177 if (Fn->isDeleted())
11178 return;
11179
11180 // See if we're deleting a function which is already known to override a
11181 // non-deleted virtual function.
11182 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11183 bool IssuedDiagnostic = false;
11184 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11185 E = MD->end_overridden_methods();
11186 I != E; ++I) {
11187 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11188 if (!IssuedDiagnostic) {
11189 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11190 IssuedDiagnostic = true;
11191 }
11192 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11193 }
11194 }
11195 }
11196
Sean Hunt10620eb2011-05-06 20:44:56 +000011197 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011198}
Sebastian Redl13e88542009-04-27 21:33:24 +000011199
Sean Hunte4246a62011-05-12 06:15:49 +000011200void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011201 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011202
11203 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011204 if (MD->getParent()->isDependentType()) {
11205 MD->setDefaulted();
11206 MD->setExplicitlyDefaulted();
11207 return;
11208 }
11209
Sean Hunte4246a62011-05-12 06:15:49 +000011210 CXXSpecialMember Member = getSpecialMember(MD);
11211 if (Member == CXXInvalid) {
11212 Diag(DefaultLoc, diag::err_default_special_members);
11213 return;
11214 }
11215
11216 MD->setDefaulted();
11217 MD->setExplicitlyDefaulted();
11218
Sean Huntcd10dec2011-05-23 23:14:04 +000011219 // If this definition appears within the record, do the checking when
11220 // the record is complete.
11221 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011222 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011223 // Find the uninstantiated declaration that actually had the '= default'
11224 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011225 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011226
Richard Smith12fef492013-03-27 00:22:47 +000011227 // If the method was defaulted on its first declaration, we will have
11228 // already performed the checking in CheckCompletedCXXClass. Such a
11229 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011230 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011231 return;
11232
Richard Smithb9d0b762012-07-27 04:22:15 +000011233 CheckExplicitlyDefaultedSpecialMember(MD);
11234
Richard Smith1d28caf2012-12-11 01:14:52 +000011235 // The exception specification is needed because we are defining the
11236 // function.
11237 ResolveExceptionSpec(DefaultLoc,
11238 MD->getType()->castAs<FunctionProtoType>());
11239
Sean Hunte4246a62011-05-12 06:15:49 +000011240 switch (Member) {
11241 case CXXDefaultConstructor: {
11242 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011243 if (!CD->isInvalidDecl())
11244 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11245 break;
11246 }
11247
11248 case CXXCopyConstructor: {
11249 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011250 if (!CD->isInvalidDecl())
11251 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011252 break;
11253 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011254
Sean Hunt2b188082011-05-14 05:23:28 +000011255 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011256 if (!MD->isInvalidDecl())
11257 DefineImplicitCopyAssignment(DefaultLoc, MD);
11258 break;
11259 }
11260
Sean Huntcb45a0f2011-05-12 22:46:25 +000011261 case CXXDestructor: {
11262 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011263 if (!DD->isInvalidDecl())
11264 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011265 break;
11266 }
11267
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011268 case CXXMoveConstructor: {
11269 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011270 if (!CD->isInvalidDecl())
11271 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011272 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011273 }
Sean Hunt82713172011-05-25 23:16:36 +000011274
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011275 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011276 if (!MD->isInvalidDecl())
11277 DefineImplicitMoveAssignment(DefaultLoc, MD);
11278 break;
11279 }
11280
11281 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011282 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011283 }
11284 } else {
11285 Diag(DefaultLoc, diag::err_default_special_members);
11286 }
11287}
11288
Sebastian Redl13e88542009-04-27 21:33:24 +000011289static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011290 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011291 Stmt *SubStmt = *CI;
11292 if (!SubStmt)
11293 continue;
11294 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011295 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011296 diag::err_return_in_constructor_handler);
11297 if (!isa<Expr>(SubStmt))
11298 SearchForReturnInStmt(Self, SubStmt);
11299 }
11300}
11301
11302void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11303 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11304 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11305 SearchForReturnInStmt(*this, Handler);
11306 }
11307}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011308
David Blaikie299adab2013-01-18 23:03:15 +000011309bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011310 const CXXMethodDecl *Old) {
11311 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11312 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11313
11314 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11315
11316 // If the calling conventions match, everything is fine
11317 if (NewCC == OldCC)
11318 return false;
11319
11320 // If either of the calling conventions are set to "default", we need to pick
11321 // something more sensible based on the target. This supports code where the
11322 // one method explicitly sets thiscall, and another has no explicit calling
11323 // convention.
11324 CallingConv Default =
11325 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11326 if (NewCC == CC_Default)
11327 NewCC = Default;
11328 if (OldCC == CC_Default)
11329 OldCC = Default;
11330
11331 // If the calling conventions still don't match, then report the error
11332 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011333 Diag(New->getLocation(),
11334 diag::err_conflicting_overriding_cc_attributes)
11335 << New->getDeclName() << New->getType() << Old->getType();
11336 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11337 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011338 }
11339
11340 return false;
11341}
11342
Mike Stump1eb44332009-09-09 15:08:12 +000011343bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011344 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011345 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11346 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011347
Chandler Carruth73857792010-02-15 11:53:20 +000011348 if (Context.hasSameType(NewTy, OldTy) ||
11349 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011350 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011351
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011352 // Check if the return types are covariant
11353 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011354
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011355 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011356 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11357 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011358 NewClassTy = NewPT->getPointeeType();
11359 OldClassTy = OldPT->getPointeeType();
11360 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011361 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11362 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11363 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11364 NewClassTy = NewRT->getPointeeType();
11365 OldClassTy = OldRT->getPointeeType();
11366 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011367 }
11368 }
Mike Stump1eb44332009-09-09 15:08:12 +000011369
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011370 // The return types aren't either both pointers or references to a class type.
11371 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011372 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011373 diag::err_different_return_type_for_overriding_virtual_function)
11374 << New->getDeclName() << NewTy << OldTy;
11375 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011376
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011377 return true;
11378 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011379
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011380 // C++ [class.virtual]p6:
11381 // If the return type of D::f differs from the return type of B::f, the
11382 // class type in the return type of D::f shall be complete at the point of
11383 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011384 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11385 if (!RT->isBeingDefined() &&
11386 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011387 diag::err_covariant_return_incomplete,
11388 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011389 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011390 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011391
Douglas Gregora4923eb2009-11-16 21:35:15 +000011392 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011393 // Check if the new class derives from the old class.
11394 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11395 Diag(New->getLocation(),
11396 diag::err_covariant_return_not_derived)
11397 << New->getDeclName() << NewTy << OldTy;
11398 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11399 return true;
11400 }
Mike Stump1eb44332009-09-09 15:08:12 +000011401
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011402 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011403 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011404 diag::err_covariant_return_inaccessible_base,
11405 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11406 // FIXME: Should this point to the return type?
11407 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011408 // FIXME: this note won't trigger for delayed access control
11409 // diagnostics, and it's impossible to get an undelayed error
11410 // here from access control during the original parse because
11411 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011412 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11413 return true;
11414 }
11415 }
Mike Stump1eb44332009-09-09 15:08:12 +000011416
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011417 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011418 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011419 Diag(New->getLocation(),
11420 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011421 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011422 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11423 return true;
11424 };
Mike Stump1eb44332009-09-09 15:08:12 +000011425
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011426
11427 // The new class type must have the same or less qualifiers as the old type.
11428 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11429 Diag(New->getLocation(),
11430 diag::err_covariant_return_type_class_type_more_qualified)
11431 << New->getDeclName() << NewTy << OldTy;
11432 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11433 return true;
11434 };
Mike Stump1eb44332009-09-09 15:08:12 +000011435
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011436 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011437}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011438
Douglas Gregor4ba31362009-12-01 17:24:26 +000011439/// \brief Mark the given method pure.
11440///
11441/// \param Method the method to be marked pure.
11442///
11443/// \param InitRange the source range that covers the "0" initializer.
11444bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011445 SourceLocation EndLoc = InitRange.getEnd();
11446 if (EndLoc.isValid())
11447 Method->setRangeEnd(EndLoc);
11448
Douglas Gregor4ba31362009-12-01 17:24:26 +000011449 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11450 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011451 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011452 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011453
11454 if (!Method->isInvalidDecl())
11455 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11456 << Method->getDeclName() << InitRange;
11457 return true;
11458}
11459
Douglas Gregor552e2992012-02-21 02:22:07 +000011460/// \brief Determine whether the given declaration is a static data member.
11461static bool isStaticDataMember(Decl *D) {
11462 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11463 if (!Var)
11464 return false;
11465
11466 return Var->isStaticDataMember();
11467}
John McCall731ad842009-12-19 09:28:58 +000011468/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11469/// an initializer for the out-of-line declaration 'Dcl'. The scope
11470/// is a fresh scope pushed for just this purpose.
11471///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011472/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11473/// static data member of class X, names should be looked up in the scope of
11474/// class X.
John McCalld226f652010-08-21 09:40:31 +000011475void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011476 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011477 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011478
John McCall731ad842009-12-19 09:28:58 +000011479 // We should only get called for declarations with scope specifiers, like:
11480 // int foo::bar;
11481 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011482 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011483
11484 // If we are parsing the initializer for a static data member, push a
11485 // new expression evaluation context that is associated with this static
11486 // data member.
11487 if (isStaticDataMember(D))
11488 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011489}
11490
11491/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011492/// initializer for the out-of-line declaration 'D'.
11493void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011494 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011495 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011496
Douglas Gregor552e2992012-02-21 02:22:07 +000011497 if (isStaticDataMember(D))
11498 PopExpressionEvaluationContext();
11499
John McCall731ad842009-12-19 09:28:58 +000011500 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011501 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011502}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011503
11504/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11505/// C++ if/switch/while/for statement.
11506/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011507DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011508 // C++ 6.4p2:
11509 // The declarator shall not specify a function or an array.
11510 // The type-specifier-seq shall not contain typedef and shall not declare a
11511 // new class or enumeration.
11512 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11513 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011514
11515 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011516 if (!Dcl)
11517 return true;
11518
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011519 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11520 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011521 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011522 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011523 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011524
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011525 return Dcl;
11526}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011527
Douglas Gregordfe65432011-07-28 19:11:31 +000011528void Sema::LoadExternalVTableUses() {
11529 if (!ExternalSource)
11530 return;
11531
11532 SmallVector<ExternalVTableUse, 4> VTables;
11533 ExternalSource->ReadUsedVTables(VTables);
11534 SmallVector<VTableUse, 4> NewUses;
11535 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11536 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11537 = VTablesUsed.find(VTables[I].Record);
11538 // Even if a definition wasn't required before, it may be required now.
11539 if (Pos != VTablesUsed.end()) {
11540 if (!Pos->second && VTables[I].DefinitionRequired)
11541 Pos->second = true;
11542 continue;
11543 }
11544
11545 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11546 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11547 }
11548
11549 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11550}
11551
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011552void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11553 bool DefinitionRequired) {
11554 // Ignore any vtable uses in unevaluated operands or for classes that do
11555 // not have a vtable.
11556 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11557 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011558 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011559 return;
11560
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011561 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011562 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011563 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11564 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11565 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11566 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011567 // If we already had an entry, check to see if we are promoting this vtable
11568 // to required a definition. If so, we need to reappend to the VTableUses
11569 // list, since we may have already processed the first entry.
11570 if (DefinitionRequired && !Pos.first->second) {
11571 Pos.first->second = true;
11572 } else {
11573 // Otherwise, we can early exit.
11574 return;
11575 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011576 }
11577
11578 // Local classes need to have their virtual members marked
11579 // immediately. For all other classes, we mark their virtual members
11580 // at the end of the translation unit.
11581 if (Class->isLocalClass())
11582 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011583 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011584 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011585}
11586
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011587bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011588 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011589 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011590 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011591
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011592 // Note: The VTableUses vector could grow as a result of marking
11593 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011594 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011595 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011596 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011597 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011598 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011599 if (!Class)
11600 continue;
11601
11602 SourceLocation Loc = VTableUses[I].second;
11603
Richard Smithb9d0b762012-07-27 04:22:15 +000011604 bool DefineVTable = true;
11605
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011606 // If this class has a key function, but that key function is
11607 // defined in another translation unit, we don't need to emit the
11608 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011609 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011610 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011611 switch (KeyFunction->getTemplateSpecializationKind()) {
11612 case TSK_Undeclared:
11613 case TSK_ExplicitSpecialization:
11614 case TSK_ExplicitInstantiationDeclaration:
11615 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011616 DefineVTable = false;
11617 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011618
11619 case TSK_ExplicitInstantiationDefinition:
11620 case TSK_ImplicitInstantiation:
11621 // We will be instantiating the key function.
11622 break;
11623 }
11624 } else if (!KeyFunction) {
11625 // If we have a class with no key function that is the subject
11626 // of an explicit instantiation declaration, suppress the
11627 // vtable; it will live with the explicit instantiation
11628 // definition.
11629 bool IsExplicitInstantiationDeclaration
11630 = Class->getTemplateSpecializationKind()
11631 == TSK_ExplicitInstantiationDeclaration;
11632 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11633 REnd = Class->redecls_end();
11634 R != REnd; ++R) {
11635 TemplateSpecializationKind TSK
11636 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11637 if (TSK == TSK_ExplicitInstantiationDeclaration)
11638 IsExplicitInstantiationDeclaration = true;
11639 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11640 IsExplicitInstantiationDeclaration = false;
11641 break;
11642 }
11643 }
11644
11645 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011646 DefineVTable = false;
11647 }
11648
11649 // The exception specifications for all virtual members may be needed even
11650 // if we are not providing an authoritative form of the vtable in this TU.
11651 // We may choose to emit it available_externally anyway.
11652 if (!DefineVTable) {
11653 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11654 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011655 }
11656
11657 // Mark all of the virtual members of this class as referenced, so
11658 // that we can build a vtable. Then, tell the AST consumer that a
11659 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011660 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011661 MarkVirtualMembersReferenced(Loc, Class);
11662 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11663 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11664
11665 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011666 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011667 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011668 const FunctionDecl *KeyFunctionDef = 0;
11669 if (!KeyFunction ||
11670 (KeyFunction->hasBody(KeyFunctionDef) &&
11671 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011672 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11673 TSK_ExplicitInstantiationDefinition
11674 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11675 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011676 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011677 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011678 VTableUses.clear();
11679
Douglas Gregor78844032011-04-22 22:25:37 +000011680 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011681}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011682
Richard Smithb9d0b762012-07-27 04:22:15 +000011683void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11684 const CXXRecordDecl *RD) {
11685 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11686 E = RD->method_end(); I != E; ++I)
11687 if ((*I)->isVirtual() && !(*I)->isPure())
11688 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11689}
11690
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011691void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11692 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011693 // Mark all functions which will appear in RD's vtable as used.
11694 CXXFinalOverriderMap FinalOverriders;
11695 RD->getFinalOverriders(FinalOverriders);
11696 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11697 E = FinalOverriders.end();
11698 I != E; ++I) {
11699 for (OverridingMethods::const_iterator OI = I->second.begin(),
11700 OE = I->second.end();
11701 OI != OE; ++OI) {
11702 assert(OI->second.size() > 0 && "no final overrider");
11703 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011704
Richard Smithff817f72012-07-07 06:59:51 +000011705 // C++ [basic.def.odr]p2:
11706 // [...] A virtual member function is used if it is not pure. [...]
11707 if (!Overrider->isPure())
11708 MarkFunctionReferenced(Loc, Overrider);
11709 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011710 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011711
11712 // Only classes that have virtual bases need a VTT.
11713 if (RD->getNumVBases() == 0)
11714 return;
11715
11716 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11717 e = RD->bases_end(); i != e; ++i) {
11718 const CXXRecordDecl *Base =
11719 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011720 if (Base->getNumVBases() == 0)
11721 continue;
11722 MarkVirtualMembersReferenced(Loc, Base);
11723 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011724}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011725
11726/// SetIvarInitializers - This routine builds initialization ASTs for the
11727/// Objective-C implementation whose ivars need be initialized.
11728void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011729 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011730 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011731 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011732 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011733 CollectIvarsToConstructOrDestruct(OID, ivars);
11734 if (ivars.empty())
11735 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011736 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011737 for (unsigned i = 0; i < ivars.size(); i++) {
11738 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011739 if (Field->isInvalidDecl())
11740 continue;
11741
Sean Huntcbb67482011-01-08 20:30:50 +000011742 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011743 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11744 InitializationKind InitKind =
11745 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11746
11747 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011748 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011749 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011750 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011751 // Note, MemberInit could actually come back empty if no initialization
11752 // is required (e.g., because it would call a trivial default constructor)
11753 if (!MemberInit.get() || MemberInit.isInvalid())
11754 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011755
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011756 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011757 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11758 SourceLocation(),
11759 MemberInit.takeAs<Expr>(),
11760 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011761 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011762
11763 // Be sure that the destructor is accessible and is marked as referenced.
11764 if (const RecordType *RecordTy
11765 = Context.getBaseElementType(Field->getType())
11766 ->getAs<RecordType>()) {
11767 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011768 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011769 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011770 CheckDestructorAccess(Field->getLocation(), Destructor,
11771 PDiag(diag::err_access_dtor_ivar)
11772 << Context.getBaseElementType(Field->getType()));
11773 }
11774 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011775 }
11776 ObjCImplementation->setIvarInitializers(Context,
11777 AllToInit.data(), AllToInit.size());
11778 }
11779}
Sean Huntfe57eef2011-05-04 05:57:24 +000011780
Sean Huntebcbe1d2011-05-04 23:29:54 +000011781static
11782void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11783 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11784 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11785 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11786 Sema &S) {
11787 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11788 CE = Current.end();
11789 if (Ctor->isInvalidDecl())
11790 return;
11791
Richard Smitha8eaf002012-08-23 06:16:52 +000011792 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11793
11794 // Target may not be determinable yet, for instance if this is a dependent
11795 // call in an uninstantiated template.
11796 if (Target) {
11797 const FunctionDecl *FNTarget = 0;
11798 (void)Target->hasBody(FNTarget);
11799 Target = const_cast<CXXConstructorDecl*>(
11800 cast_or_null<CXXConstructorDecl>(FNTarget));
11801 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011802
11803 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11804 // Avoid dereferencing a null pointer here.
11805 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11806
11807 if (!Current.insert(Canonical))
11808 return;
11809
11810 // We know that beyond here, we aren't chaining into a cycle.
11811 if (!Target || !Target->isDelegatingConstructor() ||
11812 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11813 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11814 Valid.insert(*CI);
11815 Current.clear();
11816 // We've hit a cycle.
11817 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11818 Current.count(TCanonical)) {
11819 // If we haven't diagnosed this cycle yet, do so now.
11820 if (!Invalid.count(TCanonical)) {
11821 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011822 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011823 << Ctor;
11824
Richard Smitha8eaf002012-08-23 06:16:52 +000011825 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011826 if (TCanonical != Canonical)
11827 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11828
11829 CXXConstructorDecl *C = Target;
11830 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011831 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011832 (void)C->getTargetConstructor()->hasBody(FNTarget);
11833 assert(FNTarget && "Ctor cycle through bodiless function");
11834
Richard Smitha8eaf002012-08-23 06:16:52 +000011835 C = const_cast<CXXConstructorDecl*>(
11836 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011837 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11838 }
11839 }
11840
11841 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11842 Invalid.insert(*CI);
11843 Current.clear();
11844 } else {
11845 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11846 }
11847}
11848
11849
Sean Huntfe57eef2011-05-04 05:57:24 +000011850void Sema::CheckDelegatingCtorCycles() {
11851 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11852
Sean Huntebcbe1d2011-05-04 23:29:54 +000011853 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11854 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011855
Douglas Gregor0129b562011-07-27 21:57:17 +000011856 for (DelegatingCtorDeclsType::iterator
11857 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011858 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011859 I != E; ++I)
11860 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011861
11862 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11863 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011864}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011865
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011866namespace {
11867 /// \brief AST visitor that finds references to the 'this' expression.
11868 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11869 Sema &S;
11870
11871 public:
11872 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11873
11874 bool VisitCXXThisExpr(CXXThisExpr *E) {
11875 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11876 << E->isImplicit();
11877 return false;
11878 }
11879 };
11880}
11881
11882bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11883 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11884 if (!TSInfo)
11885 return false;
11886
11887 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011888 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011889 if (!ProtoTL)
11890 return false;
11891
11892 // C++11 [expr.prim.general]p3:
11893 // [The expression this] shall not appear before the optional
11894 // cv-qualifier-seq and it shall not appear within the declaration of a
11895 // static member function (although its type and value category are defined
11896 // within a static member function as they are within a non-static member
11897 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011898 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011899 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011900 FindCXXThisExpr Finder(*this);
11901
11902 // If the return type came after the cv-qualifier-seq, check it now.
11903 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011904 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011905 return true;
11906
11907 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011908 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11909 return true;
11910
11911 return checkThisInStaticMemberFunctionAttributes(Method);
11912}
11913
11914bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11915 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11916 if (!TSInfo)
11917 return false;
11918
11919 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011920 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011921 if (!ProtoTL)
11922 return false;
11923
David Blaikie39e6ab42013-02-18 22:06:02 +000011924 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011925 FindCXXThisExpr Finder(*this);
11926
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011927 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011928 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011929 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011930 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011931 case EST_DynamicNone:
11932 case EST_MSAny:
11933 case EST_None:
11934 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011935
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011936 case EST_ComputedNoexcept:
11937 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11938 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011939
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011940 case EST_Dynamic:
11941 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011942 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011943 E != EEnd; ++E) {
11944 if (!Finder.TraverseType(*E))
11945 return true;
11946 }
11947 break;
11948 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011949
11950 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011951}
11952
11953bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11954 FindCXXThisExpr Finder(*this);
11955
11956 // Check attributes.
11957 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11958 A != AEnd; ++A) {
11959 // FIXME: This should be emitted by tblgen.
11960 Expr *Arg = 0;
11961 ArrayRef<Expr *> Args;
11962 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11963 Arg = G->getArg();
11964 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11965 Arg = G->getArg();
11966 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11967 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11968 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11969 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11970 else if (ExclusiveLockFunctionAttr *ELF
11971 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11972 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11973 else if (SharedLockFunctionAttr *SLF
11974 = dyn_cast<SharedLockFunctionAttr>(*A))
11975 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11976 else if (ExclusiveTrylockFunctionAttr *ETLF
11977 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11978 Arg = ETLF->getSuccessValue();
11979 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11980 } else if (SharedTrylockFunctionAttr *STLF
11981 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11982 Arg = STLF->getSuccessValue();
11983 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11984 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11985 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11986 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11987 Arg = LR->getArg();
11988 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11989 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11990 else if (ExclusiveLocksRequiredAttr *ELR
11991 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11992 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11993 else if (SharedLocksRequiredAttr *SLR
11994 = dyn_cast<SharedLocksRequiredAttr>(*A))
11995 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11996
11997 if (Arg && !Finder.TraverseStmt(Arg))
11998 return true;
11999
12000 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12001 if (!Finder.TraverseStmt(Args[I]))
12002 return true;
12003 }
12004 }
12005
12006 return false;
12007}
12008
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012009void
12010Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12011 ArrayRef<ParsedType> DynamicExceptions,
12012 ArrayRef<SourceRange> DynamicExceptionRanges,
12013 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012014 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012015 FunctionProtoType::ExtProtoInfo &EPI) {
12016 Exceptions.clear();
12017 EPI.ExceptionSpecType = EST;
12018 if (EST == EST_Dynamic) {
12019 Exceptions.reserve(DynamicExceptions.size());
12020 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12021 // FIXME: Preserve type source info.
12022 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12023
12024 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12025 collectUnexpandedParameterPacks(ET, Unexpanded);
12026 if (!Unexpanded.empty()) {
12027 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12028 UPPC_ExceptionType,
12029 Unexpanded);
12030 continue;
12031 }
12032
12033 // Check that the type is valid for an exception spec, and
12034 // drop it if not.
12035 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12036 Exceptions.push_back(ET);
12037 }
12038 EPI.NumExceptions = Exceptions.size();
12039 EPI.Exceptions = Exceptions.data();
12040 return;
12041 }
12042
12043 if (EST == EST_ComputedNoexcept) {
12044 // If an error occurred, there's no expression here.
12045 if (NoexceptExpr) {
12046 assert((NoexceptExpr->isTypeDependent() ||
12047 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12048 Context.BoolTy) &&
12049 "Parser should have made sure that the expression is boolean");
12050 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12051 EPI.ExceptionSpecType = EST_BasicNoexcept;
12052 return;
12053 }
12054
12055 if (!NoexceptExpr->isValueDependent())
12056 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012057 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012058 /*AllowFold*/ false).take();
12059 EPI.NoexceptExpr = NoexceptExpr;
12060 }
12061 return;
12062 }
12063}
12064
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012065/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12066Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12067 // Implicitly declared functions (e.g. copy constructors) are
12068 // __host__ __device__
12069 if (D->isImplicit())
12070 return CFT_HostDevice;
12071
12072 if (D->hasAttr<CUDAGlobalAttr>())
12073 return CFT_Global;
12074
12075 if (D->hasAttr<CUDADeviceAttr>()) {
12076 if (D->hasAttr<CUDAHostAttr>())
12077 return CFT_HostDevice;
12078 else
12079 return CFT_Device;
12080 }
12081
12082 return CFT_Host;
12083}
12084
12085bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12086 CUDAFunctionTarget CalleeTarget) {
12087 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12088 // Callable from the device only."
12089 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12090 return true;
12091
12092 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12093 // Callable from the host only."
12094 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12095 // Callable from the host only."
12096 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12097 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12098 return true;
12099
12100 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12101 return true;
12102
12103 return false;
12104}