blob: 594f79833594bd207b344d36a5f35968e629afca [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"
Richard Smith4ac537b2013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000041#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000042#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner8123a952008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattner9e979552008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 public:
Mike Stump1eb44332009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000070 };
Chris Lattner8123a952008-04-10 02:22:51 +000071
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000078 }
79
Chris Lattner9e979552008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000105 }
Chris Lattner8123a952008-04-10 02:22:51 +0000106
Douglas Gregor3996f232008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattner9e979552008-04-12 23:52:44 +0000109
Douglas Gregor796da182008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000118 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000119
John McCall045d2522013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0459f82012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner8123a952008-04-10 02:22:51 +0000147}
148
Richard Smith0b0ca472013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith7a614d82011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Sean Hunt001cad92011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
214 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
215 EEnd = Proto->exception_end();
216 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000217 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000218 Exceptions.push_back(*E);
219}
220
Richard Smith7a614d82011-06-11 17:19:42 +0000221void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000222 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000223 return;
224
225 // FIXME:
226 //
227 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000228 // [An] implicit exception-specification specifies the type-id T if and
229 // only if T is allowed by the exception-specification of a function directly
230 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000231 // function it directly invokes allows all exceptions, and f shall allow no
232 // exceptions if every function it directly invokes allows no exceptions.
233 //
234 // Note in particular that if an implicit exception-specification is generated
235 // for a function containing a throw-expression, that specification can still
236 // be noexcept(true).
237 //
238 // Note also that 'directly invoked' is not defined in the standard, and there
239 // is no indication that we should only consider potentially-evaluated calls.
240 //
241 // Ultimately we should implement the intent of the standard: the exception
242 // specification should be the set of exceptions which can be thrown by the
243 // implicit definition. For now, we assume that any non-nothrow expression can
244 // throw any exception.
245
Richard Smithe6975e92012-04-17 00:58:00 +0000246 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000247 ComputedEST = EST_None;
248}
249
Anders Carlssoned961f92009-08-25 02:29:20 +0000250bool
John McCall9ae2f072010-08-23 23:25:46 +0000251Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000252 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000253 if (RequireCompleteType(Param->getLocation(), Param->getType(),
254 diag::err_typecheck_decl_incomplete_type)) {
255 Param->setInvalidDecl();
256 return true;
257 }
258
Anders Carlssoned961f92009-08-25 02:29:20 +0000259 // C++ [dcl.fct.default]p5
260 // A default argument expression is implicitly converted (clause
261 // 4) to the parameter type. The default argument expression has
262 // the same semantic constraints as the initializer expression in
263 // a declaration of a variable of the parameter type, using the
264 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000265 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
266 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000267 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
268 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000269 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000270 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000271 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000273 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000274
Richard Smith6c3af3d2013-01-17 01:17:56 +0000275 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000276 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Anders Carlssoned961f92009-08-25 02:29:20 +0000278 // Okay: add the default argument to the parameter
279 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000281 // We have already instantiated this parameter; provide each of the
282 // instantiations with the uninstantiated default argument.
283 UnparsedDefaultArgInstantiationsMap::iterator InstPos
284 = UnparsedDefaultArgInstantiations.find(Param);
285 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
286 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
287 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
288
289 // We're done tracking this parameter's instantiations.
290 UnparsedDefaultArgInstantiations.erase(InstPos);
291 }
292
Anders Carlsson9351c172009-08-25 03:18:48 +0000293 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000294}
295
Chris Lattner8123a952008-04-10 02:22:51 +0000296/// ActOnParamDefaultArgument - Check whether the default argument
297/// provided for a function parameter is well-formed. If so, attach it
298/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000299void
John McCalld226f652010-08-21 09:40:31 +0000300Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000301 Expr *DefaultArg) {
302 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000303 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
John McCalld226f652010-08-21 09:40:31 +0000305 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000306 UnparsedDefaultArgLocs.erase(Param);
307
Chris Lattner3d1cee32008-04-08 05:04:30 +0000308 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000309 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 Diag(EqualLoc, diag::err_param_default_argument)
311 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000312 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000313 return;
314 }
315
Douglas Gregor6f526752010-12-16 08:48:57 +0000316 // Check for unexpanded parameter packs.
317 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
318 Param->setInvalidDecl();
319 return;
320 }
321
Anders Carlsson66e30672009-08-25 01:02:06 +0000322 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000323 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
324 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000325 Param->setInvalidDecl();
326 return;
327 }
Mike Stump1eb44332009-09-09 15:08:12 +0000328
John McCall9ae2f072010-08-23 23:25:46 +0000329 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000330}
331
Douglas Gregor61366e92008-12-24 00:01:03 +0000332/// ActOnParamUnparsedDefaultArgument - We've seen a default
333/// argument for a function parameter, but we can't parse it yet
334/// because we're inside a class definition. Note that this default
335/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000336void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 SourceLocation EqualLoc,
338 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000339 if (!param)
340 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
John McCalld226f652010-08-21 09:40:31 +0000342 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000343 if (Param)
344 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Anders Carlsson5e300d12009-06-12 16:51:40 +0000346 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000347}
348
Douglas Gregor72b505b2008-12-16 21:30:33 +0000349/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
350/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000351void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000352 if (!param)
353 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000354
John McCalld226f652010-08-21 09:40:31 +0000355 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Anders Carlsson5e300d12009-06-12 16:51:40 +0000357 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Anders Carlsson5e300d12009-06-12 16:51:40 +0000359 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000360}
361
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000386 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
387 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000388 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
390 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000392 << SourceRange((*Toks)[1].getLocation(),
393 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000394 delete Toks;
395 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000396 } else if (Param->getDefaultArg()) {
397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398 << Param->getDefaultArg()->getSourceRange();
399 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000400 }
401 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000402 } else if (chunk.Kind != DeclaratorChunk::Paren) {
403 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000404 }
405 }
406}
407
David Majnemerf6a144f2013-06-25 23:09:30 +0000408static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
411 if (!PVD->hasDefaultArg())
412 return false;
413 if (!PVD->hasInheritedDefaultArg())
414 return true;
415 }
416 return false;
417}
418
Craig Topper1a6eac82012-09-21 04:33:26 +0000419/// MergeCXXFunctionDecl - Merge two declarations of the same C++
420/// function, once we already know that they have the same
421/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
422/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000423bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
424 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000425 bool Invalid = false;
426
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000428 // For non-template functions, default arguments can be added in
429 // later declarations of a function in the same
430 // scope. Declarations in different scopes have completely
431 // distinct sets of default arguments. That is, declarations in
432 // inner scopes do not acquire default arguments from
433 // declarations in outer scopes, and vice versa. In a given
434 // function declaration, all parameters subsequent to a
435 // parameter with a default argument shall have default
436 // arguments supplied in this or previous declarations. A
437 // default argument shall not be redefined by a later
438 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 //
440 // C++ [dcl.fct.default]p6:
441 // Except for member functions of class templates, the default arguments
442 // in a member function definition that appears outside of the class
443 // definition are added to the set of default arguments provided by the
444 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
446 ParmVarDecl *OldParam = Old->getParamDecl(p);
447 ParmVarDecl *NewParam = New->getParamDecl(p);
448
James Molloy9cda03f2012-03-13 08:55:35 +0000449 bool OldParamHasDfl = OldParam->hasDefaultArg();
450 bool NewParamHasDfl = NewParam->hasDefaultArg();
451
452 NamedDecl *ND = Old;
453 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
454 // Ignore default parameters of old decl if they are not in
455 // the same scope.
456 OldParamHasDfl = false;
457
458 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000459
Francois Pichet8d051e02011-04-10 03:03:52 +0000460 unsigned DiagDefaultParamID =
461 diag::err_param_default_argument_redefinition;
462
463 // MSVC accepts that default parameters be redefined for member functions
464 // of template class. The new default parameter's value is ignored.
465 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000466 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000467 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
468 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // Merge the old default argument into the new parameter.
470 NewParam->setHasInheritedDefaultArg();
471 if (OldParam->hasUninstantiatedDefaultArg())
472 NewParam->setUninstantiatedDefaultArg(
473 OldParam->getUninstantiatedDefaultArg());
474 else
475 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000476 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Invalid = false;
478 }
479 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000480
Francois Pichet8cf90492011-04-10 04:58:30 +0000481 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
482 // hint here. Alternatively, we could walk the type-source information
483 // for NewParam to find the last source location in the type... but it
484 // isn't worth the effort right now. This is the kind of test case that
485 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000486 // int f(int);
487 // void g(int (*fp)(int) = f);
488 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000489 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000490 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000491
492 // Look for the function declaration where the default argument was
493 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000494 for (FunctionDecl *Older = Old->getPreviousDecl();
495 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 if (!Older->getParamDecl(p)->hasDefaultArg())
497 break;
498
499 OldParam = Older->getParamDecl(p);
500 }
501
502 Diag(OldParam->getLocation(), diag::note_previous_definition)
503 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000504 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000505 // Merge the old default argument into the new parameter.
506 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000507 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000508 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000509 if (OldParam->hasUninstantiatedDefaultArg())
510 NewParam->setUninstantiatedDefaultArg(
511 OldParam->getUninstantiatedDefaultArg());
512 else
John McCall3d6c1782010-05-04 01:53:42 +0000513 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000514 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000515 if (New->getDescribedFunctionTemplate()) {
516 // Paragraph 4, quoted above, only applies to non-template functions.
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_template_redecl)
519 << NewParam->getDefaultArgRange();
520 Diag(Old->getLocation(), diag::note_template_prev_declaration)
521 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000522 } else if (New->getTemplateSpecializationKind()
523 != TSK_ImplicitInstantiation &&
524 New->getTemplateSpecializationKind() != TSK_Undeclared) {
525 // C++ [temp.expr.spec]p21:
526 // Default function arguments shall not be specified in a declaration
527 // or a definition for one of the following explicit specializations:
528 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000529 // - the explicit specialization of a member function template;
530 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000531 // template where the class template specialization to which the
532 // member function specialization belongs is implicitly
533 // instantiated.
534 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
535 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
536 << New->getDeclName()
537 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000538 } else if (New->getDeclContext()->isDependentContext()) {
539 // C++ [dcl.fct.default]p6 (DR217):
540 // Default arguments for a member function of a class template shall
541 // be specified on the initial declaration of the member function
542 // within the class template.
543 //
544 // Reading the tea leaves a bit in DR217 and its reference to DR205
545 // leads me to the conclusion that one cannot add default function
546 // arguments for an out-of-line definition of a member function of a
547 // dependent type.
548 int WhichKind = 2;
549 if (CXXRecordDecl *Record
550 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
551 if (Record->getDescribedClassTemplate())
552 WhichKind = 0;
553 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
554 WhichKind = 1;
555 else
556 WhichKind = 2;
557 }
558
559 Diag(NewParam->getLocation(),
560 diag::err_param_default_argument_member_template_redecl)
561 << WhichKind
562 << NewParam->getDefaultArgRange();
563 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 }
565 }
566
Richard Smithb8abff62012-11-28 03:45:24 +0000567 // DR1344: If a default argument is added outside a class definition and that
568 // default argument makes the function a special member function, the program
569 // is ill-formed. This can only happen for constructors.
570 if (isa<CXXConstructorDecl>(New) &&
571 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
572 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
573 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
574 if (NewSM != OldSM) {
575 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
576 assert(NewParam->hasDefaultArg());
577 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
578 << NewParam->getDefaultArgRange() << NewSM;
579 Diag(Old->getLocation(), diag::note_previous_declaration);
580 }
581 }
582
Richard Smithff234882012-02-20 23:28:05 +0000583 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000584 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000585 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000586 if (New->isConstexpr() != Old->isConstexpr()) {
587 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
588 << New << New->isConstexpr();
589 Diag(Old->getLocation(), diag::note_previous_declaration);
590 Invalid = true;
591 }
592
David Majnemerf6a144f2013-06-25 23:09:30 +0000593 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000594 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000595 // the only declaration of the function or function template in the
596 // translation unit.
597 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
598 functionDeclHasDefaultArgument(Old)) {
599 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
600 Diag(Old->getLocation(), diag::note_previous_declaration);
601 Invalid = true;
602 }
603
Douglas Gregore13ad832010-02-12 07:32:17 +0000604 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000606
Douglas Gregorcda9c672009-02-16 17:45:42 +0000607 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000608}
609
Sebastian Redl60618fa2011-03-12 11:50:43 +0000610/// \brief Merge the exception specifications of two variable declarations.
611///
612/// This is called when there's a redeclaration of a VarDecl. The function
613/// checks if the redeclaration might have an exception specification and
614/// validates compatibility and merges the specs if necessary.
615void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
616 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000617 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000618 return;
619
620 assert(Context.hasSameType(New->getType(), Old->getType()) &&
621 "Should only be called if types are otherwise the same.");
622
623 QualType NewType = New->getType();
624 QualType OldType = Old->getType();
625
626 // We're only interested in pointers and references to functions, as well
627 // as pointers to member functions.
628 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
629 NewType = R->getPointeeType();
630 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
631 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
632 NewType = P->getPointeeType();
633 OldType = OldType->getAs<PointerType>()->getPointeeType();
634 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
635 NewType = M->getPointeeType();
636 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
637 }
638
639 if (!NewType->isFunctionProtoType())
640 return;
641
642 // There's lots of special cases for functions. For function pointers, system
643 // libraries are hopefully not as broken so that we don't need these
644 // workarounds.
645 if (CheckEquivalentExceptionSpec(
646 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
647 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
648 New->setInvalidDecl();
649 }
650}
651
Chris Lattner3d1cee32008-04-08 05:04:30 +0000652/// CheckCXXDefaultArguments - Verify that the default arguments for a
653/// function declaration are well-formed according to C++
654/// [dcl.fct.default].
655void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
656 unsigned NumParams = FD->getNumParams();
657 unsigned p;
658
659 // Find first parameter with a default argument
660 for (p = 0; p < NumParams; ++p) {
661 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000662 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 break;
664 }
665
666 // C++ [dcl.fct.default]p4:
667 // In a given function declaration, all parameters
668 // subsequent to a parameter with a default argument shall
669 // have default arguments supplied in this or previous
670 // declarations. A default argument shall not be redefined
671 // by a later declaration (not even to the same value).
672 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000673 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000674 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000675 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000676 if (Param->isInvalidDecl())
677 /* We already complained about this parameter. */;
678 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000679 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000680 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000681 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000682 else
Mike Stump1eb44332009-09-09 15:08:12 +0000683 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000684 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner3d1cee32008-04-08 05:04:30 +0000686 LastMissingDefaultArg = p;
687 }
688 }
689
690 if (LastMissingDefaultArg > 0) {
691 // Some default arguments were missing. Clear out all of the
692 // default arguments up to (and including) the last missing
693 // default argument, so that we leave the function parameters
694 // in a semantically valid state.
695 for (p = 0; p <= LastMissingDefaultArg; ++p) {
696 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000697 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000698 Param->setDefaultArg(0);
699 }
700 }
701 }
702}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000703
Richard Smith9f569cc2011-10-01 02:31:28 +0000704// CheckConstexprParameterTypes - Check whether a function's parameter types
705// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000706// diagnostic and return false.
707static bool CheckConstexprParameterTypes(Sema &SemaRef,
708 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000709 unsigned ArgIndex = 0;
710 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
711 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
712 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
713 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
714 SourceLocation ParamLoc = PD->getLocation();
715 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000716 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000717 diag::err_constexpr_non_literal_param,
718 ArgIndex+1, PD->getSourceRange(),
719 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 }
Joao Matos17d35c32012-08-31 22:18:20 +0000722 return true;
723}
724
725/// \brief Get diagnostic %select index for tag kind for
726/// record diagnostic message.
727/// WARNING: Indexes apply to particular diagnostics only!
728///
729/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000730static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000731 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000732 case TTK_Struct: return 0;
733 case TTK_Interface: return 1;
734 case TTK_Class: return 2;
735 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000736 }
Joao Matos17d35c32012-08-31 22:18:20 +0000737}
738
739// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
740// the requirements of a constexpr function definition or a constexpr
741// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000742// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000743//
Richard Smith86c3ae42012-02-13 03:54:03 +0000744// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
745bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000746 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
747 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000748 // C++11 [dcl.constexpr]p4:
749 // The definition of a constexpr constructor shall satisfy the following
750 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000752 const CXXRecordDecl *RD = MD->getParent();
753 if (RD->getNumVBases()) {
754 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
755 << isa<CXXConstructorDecl>(NewFD)
756 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
757 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
758 E = RD->vbases_end(); I != E; ++I)
759 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000761 return false;
762 }
Richard Smith35340502012-01-13 04:54:00 +0000763 }
764
765 if (!isa<CXXConstructorDecl>(NewFD)) {
766 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 // The definition of a constexpr function shall satisfy the following
768 // constraints:
769 // - it shall not be virtual;
770 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
771 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000772 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000773
Richard Smith86c3ae42012-02-13 03:54:03 +0000774 // If it's not obvious why this function is virtual, find an overridden
775 // function which uses the 'virtual' keyword.
776 const CXXMethodDecl *WrittenVirtual = Method;
777 while (!WrittenVirtual->isVirtualAsWritten())
778 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
779 if (WrittenVirtual != Method)
780 Diag(WrittenVirtual->getLocation(),
781 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000782 return false;
783 }
784
785 // - its return type shall be a literal type;
786 QualType RT = NewFD->getResultType();
787 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000788 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000789 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000791 }
792
Richard Smith35340502012-01-13 04:54:00 +0000793 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000794 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000795 return false;
796
Richard Smith9f569cc2011-10-01 02:31:28 +0000797 return true;
798}
799
800/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000801/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000802///
Richard Smitha10b9782013-04-22 15:31:51 +0000803/// \return true if the body is OK (maybe only as an extension), false if we
804/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000805static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000806 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
807 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000808 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
809 // contain only
810 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
811 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
812 switch ((*DclIt)->getKind()) {
813 case Decl::StaticAssert:
814 case Decl::Using:
815 case Decl::UsingShadow:
816 case Decl::UsingDirective:
817 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000818 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 // - static_assert-declarations
820 // - using-declarations,
821 // - using-directives,
822 continue;
823
824 case Decl::Typedef:
825 case Decl::TypeAlias: {
826 // - typedef declarations and alias-declarations that do not define
827 // classes or enumerations,
828 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
829 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
830 // Don't allow variably-modified types in constexpr functions.
831 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
832 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
833 << TL.getSourceRange() << TL.getType()
834 << isa<CXXConstructorDecl>(Dcl);
835 return false;
836 }
837 continue;
838 }
839
840 case Decl::Enum:
841 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000842 // C++1y allows types to be defined, not just declared.
843 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
844 SemaRef.Diag(DS->getLocStart(),
845 SemaRef.getLangOpts().CPlusPlus1y
846 ? diag::warn_cxx11_compat_constexpr_type_definition
847 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 continue;
850
Richard Smitha10b9782013-04-22 15:31:51 +0000851 case Decl::EnumConstant:
852 case Decl::IndirectField:
853 case Decl::ParmVar:
854 // These can only appear with other declarations which are banned in
855 // C++11 and permitted in C++1y, so ignore them.
856 continue;
857
858 case Decl::Var: {
859 // C++1y [dcl.constexpr]p3 allows anything except:
860 // a definition of a variable of non-literal type or of static or
861 // thread storage duration or for which no initialization is performed.
862 VarDecl *VD = cast<VarDecl>(*DclIt);
863 if (VD->isThisDeclarationADefinition()) {
864 if (VD->isStaticLocal()) {
865 SemaRef.Diag(VD->getLocation(),
866 diag::err_constexpr_local_var_static)
867 << isa<CXXConstructorDecl>(Dcl)
868 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
869 return false;
870 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000871 if (!VD->getType()->isDependentType() &&
872 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000873 VD->getLocation(), VD->getType(),
874 diag::err_constexpr_local_var_non_literal_type,
875 isa<CXXConstructorDecl>(Dcl)))
876 return false;
877 if (!VD->hasInit()) {
878 SemaRef.Diag(VD->getLocation(),
879 diag::err_constexpr_local_var_no_init)
880 << isa<CXXConstructorDecl>(Dcl);
881 return false;
882 }
883 }
884 SemaRef.Diag(VD->getLocation(),
885 SemaRef.getLangOpts().CPlusPlus1y
886 ? diag::warn_cxx11_compat_constexpr_local_var
887 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000889 continue;
890 }
891
892 case Decl::NamespaceAlias:
893 case Decl::Function:
894 // These are disallowed in C++11 and permitted in C++1y. Allow them
895 // everywhere as an extension.
896 if (!Cxx1yLoc.isValid())
897 Cxx1yLoc = DS->getLocStart();
898 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000899
900 default:
901 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
902 << isa<CXXConstructorDecl>(Dcl);
903 return false;
904 }
905 }
906
907 return true;
908}
909
910/// Check that the given field is initialized within a constexpr constructor.
911///
912/// \param Dcl The constexpr constructor being checked.
913/// \param Field The field being checked. This may be a member of an anonymous
914/// struct or union nested within the class being checked.
915/// \param Inits All declarations, including anonymous struct/union members and
916/// indirect members, for which any initialization was provided.
917/// \param Diagnosed Set to true if an error is produced.
918static void CheckConstexprCtorInitializer(Sema &SemaRef,
919 const FunctionDecl *Dcl,
920 FieldDecl *Field,
921 llvm::SmallSet<Decl*, 16> &Inits,
922 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000923 if (Field->isInvalidDecl())
924 return;
925
Douglas Gregord61db332011-10-10 17:22:13 +0000926 if (Field->isUnnamedBitfield())
927 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000928
929 if (Field->isAnonymousStructOrUnion() &&
930 Field->getType()->getAsCXXRecordDecl()->isEmpty())
931 return;
932
Richard Smith9f569cc2011-10-01 02:31:28 +0000933 if (!Inits.count(Field)) {
934 if (!Diagnosed) {
935 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
936 Diagnosed = true;
937 }
938 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
939 } else if (Field->isAnonymousStructOrUnion()) {
940 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
941 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
942 I != E; ++I)
943 // If an anonymous union contains an anonymous struct of which any member
944 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000945 if (!RD->isUnion() || Inits.count(*I))
946 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 }
948}
949
Richard Smitha10b9782013-04-22 15:31:51 +0000950/// Check the provided statement is allowed in a constexpr function
951/// definition.
952static bool
953CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000954 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000955 SourceLocation &Cxx1yLoc) {
956 // - its function-body shall be [...] a compound-statement that contains only
957 switch (S->getStmtClass()) {
958 case Stmt::NullStmtClass:
959 // - null statements,
960 return true;
961
962 case Stmt::DeclStmtClass:
963 // - static_assert-declarations
964 // - using-declarations,
965 // - using-directives,
966 // - typedef declarations and alias-declarations that do not define
967 // classes or enumerations,
968 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
969 return false;
970 return true;
971
972 case Stmt::ReturnStmtClass:
973 // - and exactly one return statement;
974 if (isa<CXXConstructorDecl>(Dcl)) {
975 // C++1y allows return statements in constexpr constructors.
976 if (!Cxx1yLoc.isValid())
977 Cxx1yLoc = S->getLocStart();
978 return true;
979 }
980
981 ReturnStmts.push_back(S->getLocStart());
982 return true;
983
984 case Stmt::CompoundStmtClass: {
985 // C++1y allows compound-statements.
986 if (!Cxx1yLoc.isValid())
987 Cxx1yLoc = S->getLocStart();
988
989 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
990 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
991 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
992 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
993 Cxx1yLoc))
994 return false;
995 }
996 return true;
997 }
998
999 case Stmt::AttributedStmtClass:
1000 if (!Cxx1yLoc.isValid())
1001 Cxx1yLoc = S->getLocStart();
1002 return true;
1003
1004 case Stmt::IfStmtClass: {
1005 // C++1y allows if-statements.
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008
1009 IfStmt *If = cast<IfStmt>(S);
1010 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1011 Cxx1yLoc))
1012 return false;
1013 if (If->getElse() &&
1014 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1015 Cxx1yLoc))
1016 return false;
1017 return true;
1018 }
1019
1020 case Stmt::WhileStmtClass:
1021 case Stmt::DoStmtClass:
1022 case Stmt::ForStmtClass:
1023 case Stmt::CXXForRangeStmtClass:
1024 case Stmt::ContinueStmtClass:
1025 // C++1y allows all of these. We don't allow them as extensions in C++11,
1026 // because they don't make sense without variable mutation.
1027 if (!SemaRef.getLangOpts().CPlusPlus1y)
1028 break;
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031 for (Stmt::child_range Children = S->children(); Children; ++Children)
1032 if (*Children &&
1033 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1034 Cxx1yLoc))
1035 return false;
1036 return true;
1037
1038 case Stmt::SwitchStmtClass:
1039 case Stmt::CaseStmtClass:
1040 case Stmt::DefaultStmtClass:
1041 case Stmt::BreakStmtClass:
1042 // C++1y allows switch-statements, and since they don't need variable
1043 // mutation, we can reasonably allow them in C++11 as an extension.
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 default:
1054 if (!isa<Expr>(S))
1055 break;
1056
1057 // C++1y allows expression-statements.
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 return true;
1061 }
1062
1063 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1064 << isa<CXXConstructorDecl>(Dcl);
1065 return false;
1066}
1067
Richard Smith9f569cc2011-10-01 02:31:28 +00001068/// Check the body for the given constexpr function declaration only contains
1069/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1070///
1071/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001072bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001073 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001074 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001075 // The definition of a constexpr function shall satisfy the following
1076 // constraints: [...]
1077 // - its function-body shall be = delete, = default, or a
1078 // compound-statement
1079 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 // In the definition of a constexpr constructor, [...]
1082 // - its function-body shall not be a function-try-block;
1083 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1084 << isa<CXXConstructorDecl>(Dcl);
1085 return false;
1086 }
1087
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001088 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001089
1090 // - its function-body shall be [...] a compound-statement that contains only
1091 // [... list of cases ...]
1092 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1093 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001094 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1095 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001096 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1097 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001098 }
1099
Richard Smitha10b9782013-04-22 15:31:51 +00001100 if (Cxx1yLoc.isValid())
1101 Diag(Cxx1yLoc,
1102 getLangOpts().CPlusPlus1y
1103 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1104 : diag::ext_constexpr_body_invalid_stmt)
1105 << isa<CXXConstructorDecl>(Dcl);
1106
Richard Smith9f569cc2011-10-01 02:31:28 +00001107 if (const CXXConstructorDecl *Constructor
1108 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1109 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001110 // DR1359:
1111 // - every non-variant non-static data member and base class sub-object
1112 // shall be initialized;
1113 // - if the class is a non-empty union, or for each non-empty anonymous
1114 // union member of a non-union class, exactly one non-static data member
1115 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001116 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001117 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001118 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1119 return false;
1120 }
Richard Smith6e433752011-10-10 16:38:04 +00001121 } else if (!Constructor->isDependentContext() &&
1122 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001123 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1124
1125 // Skip detailed checking if we have enough initializers, and we would
1126 // allow at most one initializer per member.
1127 bool AnyAnonStructUnionMembers = false;
1128 unsigned Fields = 0;
1129 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1130 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001131 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 AnyAnonStructUnionMembers = true;
1133 break;
1134 }
1135 }
1136 if (AnyAnonStructUnionMembers ||
1137 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1138 // Check initialization of non-static data members. Base classes are
1139 // always initialized so do not need to be checked. Dependent bases
1140 // might not have initializers in the member initializer list.
1141 llvm::SmallSet<Decl*, 16> Inits;
1142 for (CXXConstructorDecl::init_const_iterator
1143 I = Constructor->init_begin(), E = Constructor->init_end();
1144 I != E; ++I) {
1145 if (FieldDecl *FD = (*I)->getMember())
1146 Inits.insert(FD);
1147 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1148 Inits.insert(ID->chain_begin(), ID->chain_end());
1149 }
1150
1151 bool Diagnosed = false;
1152 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001154 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001155 if (Diagnosed)
1156 return false;
1157 }
1158 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001159 } else {
1160 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001161 // C++1y doesn't require constexpr functions to contain a 'return'
1162 // statement. We still do, unless the return type is void, because
1163 // otherwise if there's no return statement, the function cannot
1164 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001165 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001166 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001167 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1168 : diag::err_constexpr_body_no_return);
1169 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001170 }
1171 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001172 Diag(ReturnStmts.back(),
1173 getLangOpts().CPlusPlus1y
1174 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1175 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1177 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001178 }
1179 }
1180
Richard Smith5ba73e12012-02-04 00:33:54 +00001181 // C++11 [dcl.constexpr]p5:
1182 // if no function argument values exist such that the function invocation
1183 // substitution would produce a constant expression, the program is
1184 // ill-formed; no diagnostic required.
1185 // C++11 [dcl.constexpr]p3:
1186 // - every constructor call and implicit conversion used in initializing the
1187 // return value shall be one of those allowed in a constant expression.
1188 // C++11 [dcl.constexpr]p4:
1189 // - every constructor involved in initializing non-static data members and
1190 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001191 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001192 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001193 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001194 << isa<CXXConstructorDecl>(Dcl);
1195 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1196 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001197 // Don't return false here: we allow this for compatibility in
1198 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001199 }
1200
Richard Smith9f569cc2011-10-01 02:31:28 +00001201 return true;
1202}
1203
Douglas Gregorb48fe382008-10-31 09:07:45 +00001204/// isCurrentClassName - Determine whether the identifier II is the
1205/// name of the class type currently being defined. In the case of
1206/// nested classes, this will only return true if II is the name of
1207/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001208bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1209 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001211
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001212 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001213 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001214 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001215 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1216 } else
1217 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1218
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001219 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001220 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001221 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001222}
1223
Douglas Gregor229d47a2012-11-10 07:24:09 +00001224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227 const CXXRecordDecl *Current) {
1228 SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230 Class = Class->getCanonicalDecl();
1231 while (true) {
1232 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233 E = Current->bases_end();
1234 I != E; ++I) {
1235 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236 if (!Base)
1237 continue;
1238
1239 Base = Base->getDefinition();
1240 if (!Base)
1241 continue;
1242
1243 if (Base->getCanonicalDecl() == Class)
1244 return true;
1245
1246 Queue.push_back(Base);
1247 }
1248
1249 if (Queue.empty())
1250 return false;
1251
Robert Wilhelm344472e2013-08-23 16:11:15 +00001252 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001253 }
1254
1255 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001256}
1257
Mike Stump1eb44332009-09-09 15:08:12 +00001258/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001259///
1260/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1261/// and returns NULL otherwise.
1262CXXBaseSpecifier *
1263Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1264 SourceRange SpecifierRange,
1265 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001266 TypeSourceInfo *TInfo,
1267 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001268 QualType BaseType = TInfo->getType();
1269
Douglas Gregor2943aed2009-03-03 04:44:36 +00001270 // C++ [class.union]p1:
1271 // A union shall not have base classes.
1272 if (Class->isUnion()) {
1273 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1274 << SpecifierRange;
1275 return 0;
1276 }
1277
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001278 if (EllipsisLoc.isValid() &&
1279 !TInfo->getType()->containsUnexpandedParameterPack()) {
1280 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1281 << TInfo->getTypeLoc().getSourceRange();
1282 EllipsisLoc = SourceLocation();
1283 }
Douglas Gregord777e282012-11-10 01:18:17 +00001284
1285 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1286
1287 if (BaseType->isDependentType()) {
1288 // Make sure that we don't have circular inheritance among our dependent
1289 // bases. For non-dependent bases, the check for completeness below handles
1290 // this.
1291 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1292 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1293 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001294 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001295 Diag(BaseLoc, diag::err_circular_inheritance)
1296 << BaseType << Context.getTypeDeclType(Class);
1297
1298 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1299 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1300 << BaseType;
1301
1302 return 0;
1303 }
1304 }
1305
Mike Stump1eb44332009-09-09 15:08:12 +00001306 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001307 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001308 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001309 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001310
1311 // Base specifiers must be record types.
1312 if (!BaseType->isRecordType()) {
1313 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1314 return 0;
1315 }
1316
1317 // C++ [class.union]p1:
1318 // A union shall not be used as a base class.
1319 if (BaseType->isUnionType()) {
1320 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1321 return 0;
1322 }
1323
1324 // C++ [class.derived]p2:
1325 // The class-name in a base-specifier shall not be an incompletely
1326 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001327 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001328 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001329 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001330 return 0;
John McCall572fc622010-08-17 07:23:57 +00001331 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001332
Eli Friedman1d954f62009-08-15 21:55:26 +00001333 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001334 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001335 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001336 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001337 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001338 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001339 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001340
Anders Carlsson1d209272011-03-25 14:55:14 +00001341 // C++ [class]p3:
1342 // If a class is marked final and it appears as a base-type-specifier in
1343 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001344 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001345 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1346 << CXXBaseDecl->getDeclName();
1347 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1348 << CXXBaseDecl->getDeclName();
1349 return 0;
1350 }
1351
John McCall572fc622010-08-17 07:23:57 +00001352 if (BaseDecl->isInvalidDecl())
1353 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001354
1355 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001356 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001357 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001358 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001359}
1360
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001361/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1362/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001363/// example:
1364/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001365/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001366BaseResult
John McCalld226f652010-08-21 09:40:31 +00001367Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001368 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001369 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001370 ParsedType basetype, SourceLocation BaseLoc,
1371 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001372 if (!classdecl)
1373 return true;
1374
Douglas Gregor40808ce2009-03-09 23:48:35 +00001375 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001376 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001377 if (!Class)
1378 return true;
1379
Richard Smith05321402013-02-19 23:47:15 +00001380 // We do not support any C++11 attributes on base-specifiers yet.
1381 // Diagnose any attributes we see.
1382 if (!Attributes.empty()) {
1383 for (AttributeList *Attr = Attributes.getList(); Attr;
1384 Attr = Attr->getNext()) {
1385 if (Attr->isInvalid() ||
1386 Attr->getKind() == AttributeList::IgnoredAttribute)
1387 continue;
1388 Diag(Attr->getLoc(),
1389 Attr->getKind() == AttributeList::UnknownAttribute
1390 ? diag::warn_unknown_attribute_ignored
1391 : diag::err_base_specifier_attribute)
1392 << Attr->getName();
1393 }
1394 }
1395
Nick Lewycky56062202010-07-26 16:56:01 +00001396 TypeSourceInfo *TInfo = 0;
1397 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001398
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001399 if (EllipsisLoc.isInvalid() &&
1400 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001401 UPPC_BaseType))
1402 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001403
Douglas Gregor2943aed2009-03-03 04:44:36 +00001404 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001405 Virtual, Access, TInfo,
1406 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001407 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001408 else
1409 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Douglas Gregor2943aed2009-03-03 04:44:36 +00001411 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001412}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001413
Douglas Gregor2943aed2009-03-03 04:44:36 +00001414/// \brief Performs the actual work of attaching the given base class
1415/// specifiers to a C++ class.
1416bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1417 unsigned NumBases) {
1418 if (NumBases == 0)
1419 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001420
1421 // Used to keep track of which base types we have already seen, so
1422 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001423 // that the key is always the unqualified canonical type of the base
1424 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001425 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1426
1427 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001428 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001430 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001431 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001432 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001433 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001434
1435 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1436 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001437 // C++ [class.mi]p3:
1438 // A class shall not be specified as a direct base class of a
1439 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001440 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001441 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001442 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001443 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001444
1445 // Delete the duplicate base class specifier; we're going to
1446 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001447 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001448
1449 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001450 } else {
1451 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001452 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001453 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001454 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1455 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1456 if (Class->isInterface() &&
1457 (!RD->isInterface() ||
1458 KnownBase->getAccessSpecifier() != AS_public)) {
1459 // The Microsoft extension __interface does not permit bases that
1460 // are not themselves public interfaces.
1461 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1462 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1463 << RD->getSourceRange();
1464 Invalid = true;
1465 }
1466 if (RD->hasAttr<WeakAttr>())
1467 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1468 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001469 }
1470 }
1471
1472 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001473 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001474
1475 // Delete the remaining (good) base class specifiers, since their
1476 // data has been copied into the CXXRecordDecl.
1477 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001478 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001479
1480 return Invalid;
1481}
1482
1483/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1484/// class, after checking whether there are any duplicate base
1485/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001486void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001487 unsigned NumBases) {
1488 if (!ClassDecl || !Bases || !NumBases)
1489 return;
1490
1491 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001492 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001493}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001494
Douglas Gregora8f32e02009-10-06 17:59:45 +00001495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001508
1509 // If either the base or the derived type is invalid, don't try to
1510 // check whether one is derived from the other.
1511 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1512 return false;
1513
John McCall86ff3082010-02-04 22:26:26 +00001514 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1515 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001516}
1517
1518/// \brief Determine whether the type \p Derived is a C++ class that is
1519/// derived from the type \p Base.
1520bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001521 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001522 return false;
1523
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001524 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001525 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001526 return false;
1527
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001528 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001529 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001530 return false;
1531
Douglas Gregora8f32e02009-10-06 17:59:45 +00001532 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1533}
1534
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001535void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001536 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001537 assert(BasePathArray.empty() && "Base path array must be empty!");
1538 assert(Paths.isRecordingPaths() && "Must record paths!");
1539
1540 const CXXBasePath &Path = Paths.front();
1541
1542 // We first go backward and check if we have a virtual base.
1543 // FIXME: It would be better if CXXBasePath had the base specifier for
1544 // the nearest virtual base.
1545 unsigned Start = 0;
1546 for (unsigned I = Path.size(); I != 0; --I) {
1547 if (Path[I - 1].Base->isVirtual()) {
1548 Start = I - 1;
1549 break;
1550 }
1551 }
1552
1553 // Now add all bases.
1554 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001555 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001556}
1557
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001558/// \brief Determine whether the given base path includes a virtual
1559/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001560bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1561 for (CXXCastPath::const_iterator B = BasePath.begin(),
1562 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001563 B != BEnd; ++B)
1564 if ((*B)->isVirtual())
1565 return true;
1566
1567 return false;
1568}
1569
Douglas Gregora8f32e02009-10-06 17:59:45 +00001570/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1571/// conversion (where Derived and Base are class types) is
1572/// well-formed, meaning that the conversion is unambiguous (and
1573/// that all of the base classes are accessible). Returns true
1574/// and emits a diagnostic if the code is ill-formed, returns false
1575/// otherwise. Loc is the location where this routine should point to
1576/// if there is an error, and Range is the source range to highlight
1577/// if there is an error.
1578bool
1579Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001580 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001581 unsigned AmbigiousBaseConvID,
1582 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001583 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001584 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001585 // First, determine whether the path from Derived to Base is
1586 // ambiguous. This is slightly more expensive than checking whether
1587 // the Derived to Base conversion exists, because here we need to
1588 // explore multiple paths to determine if there is an ambiguity.
1589 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1590 /*DetectVirtual=*/false);
1591 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1592 assert(DerivationOkay &&
1593 "Can only be used with a derived-to-base conversion");
1594 (void)DerivationOkay;
1595
1596 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001597 if (InaccessibleBaseID) {
1598 // Check that the base class can be accessed.
1599 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1600 InaccessibleBaseID)) {
1601 case AR_inaccessible:
1602 return true;
1603 case AR_accessible:
1604 case AR_dependent:
1605 case AR_delayed:
1606 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001607 }
John McCall6b2accb2010-02-10 09:31:12 +00001608 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001609
1610 // Build a base path if necessary.
1611 if (BasePath)
1612 BuildBasePathArray(Paths, *BasePath);
1613 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001614 }
1615
David Majnemer2f686692013-06-22 06:43:58 +00001616 if (AmbigiousBaseConvID) {
1617 // We know that the derived-to-base conversion is ambiguous, and
1618 // we're going to produce a diagnostic. Perform the derived-to-base
1619 // search just one more time to compute all of the possible paths so
1620 // that we can print them out. This is more expensive than any of
1621 // the previous derived-to-base checks we've done, but at this point
1622 // performance isn't as much of an issue.
1623 Paths.clear();
1624 Paths.setRecordingPaths(true);
1625 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1626 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1627 (void)StillOkay;
1628
1629 // Build up a textual representation of the ambiguous paths, e.g.,
1630 // D -> B -> A, that will be used to illustrate the ambiguous
1631 // conversions in the diagnostic. We only print one of the paths
1632 // to each base class subobject.
1633 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1634
1635 Diag(Loc, AmbigiousBaseConvID)
1636 << Derived << Base << PathDisplayStr << Range << Name;
1637 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001638 return true;
1639}
1640
1641bool
1642Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001643 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001644 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001645 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001646 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001647 IgnoreAccess ? 0
1648 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001649 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001650 Loc, Range, DeclarationName(),
1651 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001652}
1653
1654
1655/// @brief Builds a string representing ambiguous paths from a
1656/// specific derived class to different subobjects of the same base
1657/// class.
1658///
1659/// This function builds a string that can be used in error messages
1660/// to show the different paths that one can take through the
1661/// inheritance hierarchy to go from the derived class to different
1662/// subobjects of a base class. The result looks something like this:
1663/// @code
1664/// struct D -> struct B -> struct A
1665/// struct D -> struct C -> struct A
1666/// @endcode
1667std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1668 std::string PathDisplayStr;
1669 std::set<unsigned> DisplayedPaths;
1670 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1671 Path != Paths.end(); ++Path) {
1672 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1673 // We haven't displayed a path to this particular base
1674 // class subobject yet.
1675 PathDisplayStr += "\n ";
1676 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1677 for (CXXBasePath::const_iterator Element = Path->begin();
1678 Element != Path->end(); ++Element)
1679 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1680 }
1681 }
1682
1683 return PathDisplayStr;
1684}
1685
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001686//===----------------------------------------------------------------------===//
1687// C++ class member Handling
1688//===----------------------------------------------------------------------===//
1689
Abramo Bagnara6206d532010-06-05 05:09:32 +00001690/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001691bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1692 SourceLocation ASLoc,
1693 SourceLocation ColonLoc,
1694 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001695 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001696 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001697 ASLoc, ColonLoc);
1698 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001699 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001700}
1701
Richard Smitha4b39652012-08-06 03:25:17 +00001702/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001703void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001704 if (D->isInvalidDecl())
1705 return;
1706
Eli Friedmandae92712013-09-05 23:51:03 +00001707 // We only care about "override" and "final" declarations.
1708 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1709 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001710
Eli Friedmandae92712013-09-05 23:51:03 +00001711 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001712
Eli Friedmandae92712013-09-05 23:51:03 +00001713 // We can't check dependent instance methods.
1714 if (MD && MD->isInstance() &&
1715 (MD->getParent()->hasAnyDependentBases() ||
1716 MD->getType()->isDependentType()))
1717 return;
1718
1719 if (MD && !MD->isVirtual()) {
1720 // If we have a non-virtual method, check if if hides a virtual method.
1721 // (In that case, it's most likely the method has the wrong type.)
1722 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1723 FindHiddenVirtualMethods(MD, OverloadedMethods);
1724
1725 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001726 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1727 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001728 diag::override_keyword_hides_virtual_member_function)
1729 << "override" << (OverloadedMethods.size() > 1);
1730 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001731 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001732 diag::override_keyword_hides_virtual_member_function)
1733 << "final" << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001734 }
Eli Friedmandae92712013-09-05 23:51:03 +00001735 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1736 MD->setInvalidDecl();
1737 return;
1738 }
1739 // Fall through into the general case diagnostic.
1740 // FIXME: We might want to attempt typo correction here.
1741 }
1742
1743 if (!MD || !MD->isVirtual()) {
1744 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1745 Diag(OA->getLocation(),
1746 diag::override_keyword_only_allowed_on_virtual_member_functions)
1747 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1748 D->dropAttr<OverrideAttr>();
1749 }
1750 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1751 Diag(FA->getLocation(),
1752 diag::override_keyword_only_allowed_on_virtual_member_functions)
1753 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1754 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001755 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001756 return;
1757 }
Richard Smitha4b39652012-08-06 03:25:17 +00001758
Richard Smitha4b39652012-08-06 03:25:17 +00001759 // C++11 [class.virtual]p5:
1760 // If a virtual function is marked with the virt-specifier override and
1761 // does not override a member function of a base class, the program is
1762 // ill-formed.
1763 bool HasOverriddenMethods =
1764 MD->begin_overridden_methods() != MD->end_overridden_methods();
1765 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1766 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1767 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001768}
1769
Richard Smitha4b39652012-08-06 03:25:17 +00001770/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001771/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001772/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001773bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1774 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001775 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001776 return false;
1777
1778 Diag(New->getLocation(), diag::err_final_function_overridden)
1779 << New->getDeclName();
1780 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1781 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001782}
1783
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001784static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001785 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1786 // FIXME: Destruction of ObjC lifetime types has side-effects.
1787 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1788 return !RD->isCompleteDefinition() ||
1789 !RD->hasTrivialDefaultConstructor() ||
1790 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001791 return false;
1792}
1793
John McCall76da55d2013-04-16 07:28:30 +00001794static AttributeList *getMSPropertyAttr(AttributeList *list) {
1795 for (AttributeList* it = list; it != 0; it = it->getNext())
1796 if (it->isDeclspecPropertyAttribute())
1797 return it;
1798 return 0;
1799}
1800
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001801/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1802/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001803/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001804/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1805/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001806NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001807Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001808 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001809 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001810 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001811 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001812 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1813 DeclarationName Name = NameInfo.getName();
1814 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001815
1816 // For anonymous bitfields, the location should point to the type.
1817 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001818 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001819
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001820 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001821
John McCall4bde1e12010-06-04 08:34:12 +00001822 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001823 assert(!DS.isFriendSpecified());
1824
Richard Smith1ab0d902011-06-25 02:28:38 +00001825 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001826
John McCalle402e722012-09-25 07:32:39 +00001827 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1828 // The Microsoft extension __interface only permits public member functions
1829 // and prohibits constructors, destructors, operators, non-public member
1830 // functions, static methods and data members.
1831 unsigned InvalidDecl;
1832 bool ShowDeclName = true;
1833 if (!isFunc)
1834 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1835 else if (AS != AS_public)
1836 InvalidDecl = 2;
1837 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1838 InvalidDecl = 3;
1839 else switch (Name.getNameKind()) {
1840 case DeclarationName::CXXConstructorName:
1841 InvalidDecl = 4;
1842 ShowDeclName = false;
1843 break;
1844
1845 case DeclarationName::CXXDestructorName:
1846 InvalidDecl = 5;
1847 ShowDeclName = false;
1848 break;
1849
1850 case DeclarationName::CXXOperatorName:
1851 case DeclarationName::CXXConversionFunctionName:
1852 InvalidDecl = 6;
1853 break;
1854
1855 default:
1856 InvalidDecl = 0;
1857 break;
1858 }
1859
1860 if (InvalidDecl) {
1861 if (ShowDeclName)
1862 Diag(Loc, diag::err_invalid_member_in_interface)
1863 << (InvalidDecl-1) << Name;
1864 else
1865 Diag(Loc, diag::err_invalid_member_in_interface)
1866 << (InvalidDecl-1) << "";
1867 return 0;
1868 }
1869 }
1870
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001871 // C++ 9.2p6: A member shall not be declared to have automatic storage
1872 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001873 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1874 // data members and cannot be applied to names declared const or static,
1875 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001876 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001877 case DeclSpec::SCS_unspecified:
1878 case DeclSpec::SCS_typedef:
1879 case DeclSpec::SCS_static:
1880 break;
1881 case DeclSpec::SCS_mutable:
1882 if (isFunc) {
1883 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Richard Smithec642442013-04-12 22:46:28 +00001885 // FIXME: It would be nicer if the keyword was ignored only for this
1886 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001887 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001888 }
1889 break;
1890 default:
1891 Diag(DS.getStorageClassSpecLoc(),
1892 diag::err_storageclass_invalid_for_member);
1893 D.getMutableDeclSpec().ClearStorageClassSpecs();
1894 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001895 }
1896
Sebastian Redl669d5d72008-11-14 23:42:31 +00001897 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1898 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001899 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001900
David Blaikie1d87fba2013-01-30 01:22:18 +00001901 if (DS.isConstexprSpecified() && isInstField) {
1902 SemaDiagnosticBuilder B =
1903 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1904 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1905 if (InitStyle == ICIS_NoInit) {
1906 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1907 D.getMutableDeclSpec().ClearConstexprSpec();
1908 const char *PrevSpec;
1909 unsigned DiagID;
1910 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1911 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001912 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001913 assert(!Failed && "Making a constexpr member const shouldn't fail");
1914 } else {
1915 B << 1;
1916 const char *PrevSpec;
1917 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001918 if (D.getMutableDeclSpec().SetStorageClassSpec(
1919 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001920 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001921 "This is the only DeclSpec that should fail to be applied");
1922 B << 1;
1923 } else {
1924 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1925 isInstField = false;
1926 }
1927 }
1928 }
1929
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001930 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001931 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001932 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001933
1934 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001935 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001936 Diag(Loc, diag::err_bad_variable_name)
1937 << Name;
1938 return 0;
1939 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001940
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001941 IdentifierInfo *II = Name.getAsIdentifierInfo();
1942
Douglas Gregorf2503652011-09-21 14:40:46 +00001943 // Member field could not be with "template" keyword.
1944 // So TemplateParameterLists should be empty in this case.
1945 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001946 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001947 if (TemplateParams->size()) {
1948 // There is no such thing as a member field template.
1949 Diag(D.getIdentifierLoc(), diag::err_template_member)
1950 << II
1951 << SourceRange(TemplateParams->getTemplateLoc(),
1952 TemplateParams->getRAngleLoc());
1953 } else {
1954 // There is an extraneous 'template<>' for this member.
1955 Diag(TemplateParams->getTemplateLoc(),
1956 diag::err_template_member_noparams)
1957 << II
1958 << SourceRange(TemplateParams->getTemplateLoc(),
1959 TemplateParams->getRAngleLoc());
1960 }
1961 return 0;
1962 }
1963
Douglas Gregor922fff22010-10-13 22:19:53 +00001964 if (SS.isSet() && !SS.isInvalid()) {
1965 // The user provided a superfluous scope specifier inside a class
1966 // definition:
1967 //
1968 // class X {
1969 // int X::member;
1970 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001971 if (DeclContext *DC = computeDeclContext(SS, false))
1972 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001973 else
1974 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1975 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001976
Douglas Gregor922fff22010-10-13 22:19:53 +00001977 SS.clear();
1978 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001979
John McCall76da55d2013-04-16 07:28:30 +00001980 AttributeList *MSPropertyAttr =
1981 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001982 if (MSPropertyAttr) {
1983 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1984 BitWidth, InitStyle, AS, MSPropertyAttr);
1985 if (!Member)
1986 return 0;
1987 isInstField = false;
1988 } else {
1989 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1990 BitWidth, InitStyle, AS);
1991 assert(Member && "HandleField never returns null");
1992 }
1993 } else {
1994 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1995
1996 Member = HandleDeclarator(S, D, TemplateParameterLists);
1997 if (!Member)
1998 return 0;
1999
2000 // Non-instance-fields can't have a bitfield.
2001 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002002 if (Member->isInvalidDecl()) {
2003 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002004 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002005 // C++ 9.6p3: A bit-field shall not be a static member.
2006 // "static member 'A' cannot be a bit-field"
2007 Diag(Loc, diag::err_static_not_bitfield)
2008 << Name << BitWidth->getSourceRange();
2009 } else if (isa<TypedefDecl>(Member)) {
2010 // "typedef member 'x' cannot be a bit-field"
2011 Diag(Loc, diag::err_typedef_not_bitfield)
2012 << Name << BitWidth->getSourceRange();
2013 } else {
2014 // A function typedef ("typedef int f(); f a;").
2015 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2016 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002017 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002018 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Chris Lattner8b963ef2009-03-05 23:01:03 +00002021 BitWidth = 0;
2022 Member->setInvalidDecl();
2023 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002024
2025 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Larisse Voufoef4579c2013-08-06 01:03:05 +00002027 // If we have declared a member function template or static data member
2028 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002029 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2030 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002031 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2032 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002033 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002034
Richard Smitha4b39652012-08-06 03:25:17 +00002035 if (VS.isOverrideSpecified())
2036 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2037 if (VS.isFinalSpecified())
2038 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002039
Douglas Gregorf5251602011-03-08 17:10:18 +00002040 if (VS.getLastLocation().isValid()) {
2041 // Update the end location of a method that has a virt-specifiers.
2042 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2043 MD->setRangeEnd(VS.getLastLocation());
2044 }
Richard Smitha4b39652012-08-06 03:25:17 +00002045
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002046 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002047
Douglas Gregor10bd3682008-11-17 22:58:34 +00002048 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002049
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002050 if (isInstField) {
2051 FieldDecl *FD = cast<FieldDecl>(Member);
2052 FieldCollector->Add(FD);
2053
2054 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2055 FD->getLocation())
2056 != DiagnosticsEngine::Ignored) {
2057 // Remember all explicit private FieldDecls that have a name, no side
2058 // effects and are not part of a dependent type declaration.
2059 if (!FD->isImplicit() && FD->getDeclName() &&
2060 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002061 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002062 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002063 !InitializationHasSideEffects(*FD))
2064 UnusedPrivateFields.insert(FD);
2065 }
2066 }
2067
John McCalld226f652010-08-21 09:40:31 +00002068 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002069}
2070
Hans Wennborg471f9852012-09-18 15:58:06 +00002071namespace {
2072 class UninitializedFieldVisitor
2073 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2074 Sema &S;
2075 ValueDecl *VD;
2076 public:
2077 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2078 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002079 S(S) {
2080 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2081 this->VD = IFD->getAnonField();
2082 else
2083 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002084 }
2085
2086 void HandleExpr(Expr *E) {
2087 if (!E) return;
2088
2089 // Expressions like x(x) sometimes lack the surrounding expressions
2090 // but need to be checked anyways.
2091 HandleValue(E);
2092 Visit(E);
2093 }
2094
2095 void HandleValue(Expr *E) {
2096 E = E->IgnoreParens();
2097
2098 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2099 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002100 return;
2101
2102 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2103 // or union.
2104 MemberExpr *FieldME = ME;
2105
Hans Wennborg471f9852012-09-18 15:58:06 +00002106 Expr *Base = E;
2107 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002108 ME = cast<MemberExpr>(Base);
2109
2110 if (isa<VarDecl>(ME->getMemberDecl()))
2111 return;
2112
2113 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2114 if (!FD->isAnonymousStructOrUnion())
2115 FieldME = ME;
2116
Hans Wennborg471f9852012-09-18 15:58:06 +00002117 Base = ME->getBase();
2118 }
2119
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002120 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002121 unsigned diag = VD->getType()->isReferenceType()
2122 ? diag::warn_reference_field_is_uninit
2123 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002124 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002125 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002126 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002127 }
2128
2129 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2130 HandleValue(CO->getTrueExpr());
2131 HandleValue(CO->getFalseExpr());
2132 return;
2133 }
2134
2135 if (BinaryConditionalOperator *BCO =
2136 dyn_cast<BinaryConditionalOperator>(E)) {
2137 HandleValue(BCO->getCommon());
2138 HandleValue(BCO->getFalseExpr());
2139 return;
2140 }
2141
2142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2143 switch (BO->getOpcode()) {
2144 default:
2145 return;
2146 case(BO_PtrMemD):
2147 case(BO_PtrMemI):
2148 HandleValue(BO->getLHS());
2149 return;
2150 case(BO_Comma):
2151 HandleValue(BO->getRHS());
2152 return;
2153 }
2154 }
2155 }
2156
2157 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2158 if (E->getCastKind() == CK_LValueToRValue)
2159 HandleValue(E->getSubExpr());
2160
2161 Inherited::VisitImplicitCastExpr(E);
2162 }
2163
2164 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2165 Expr *Callee = E->getCallee();
2166 if (isa<MemberExpr>(Callee))
2167 HandleValue(Callee);
2168
2169 Inherited::VisitCXXMemberCallExpr(E);
2170 }
2171 };
2172 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2173 ValueDecl *VD) {
2174 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2175 }
2176} // namespace
2177
Richard Smith7a614d82011-06-11 17:19:42 +00002178/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002179/// in-class initializer for a non-static C++ class member, and after
2180/// instantiating an in-class initializer in a class template. Such actions
2181/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002182void
Richard Smithca523302012-06-10 03:12:00 +00002183Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002184 Expr *InitExpr) {
2185 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002186 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2187 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002188
2189 if (!InitExpr) {
2190 FD->setInvalidDecl();
2191 FD->removeInClassInitializer();
2192 return;
2193 }
2194
Peter Collingbournefef21892011-10-23 18:59:44 +00002195 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2196 FD->setInvalidDecl();
2197 FD->removeInClassInitializer();
2198 return;
2199 }
2200
Hans Wennborg471f9852012-09-18 15:58:06 +00002201 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2202 != DiagnosticsEngine::Ignored) {
2203 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2204 }
2205
Richard Smith7a614d82011-06-11 17:19:42 +00002206 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002207 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002208 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002209 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002210 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002211 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002212 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2213 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002214 if (Init.isInvalid()) {
2215 FD->setInvalidDecl();
2216 return;
2217 }
Richard Smith7a614d82011-06-11 17:19:42 +00002218 }
2219
Richard Smith41956372013-01-14 22:39:08 +00002220 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002221 // The initialization of each base and member constitutes a
2222 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002223 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002224 if (Init.isInvalid()) {
2225 FD->setInvalidDecl();
2226 return;
2227 }
2228
2229 InitExpr = Init.release();
2230
2231 FD->setInClassInitializer(InitExpr);
2232}
2233
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002234/// \brief Find the direct and/or virtual base specifiers that
2235/// correspond to the given base type, for use in base initialization
2236/// within a constructor.
2237static bool FindBaseInitializer(Sema &SemaRef,
2238 CXXRecordDecl *ClassDecl,
2239 QualType BaseType,
2240 const CXXBaseSpecifier *&DirectBaseSpec,
2241 const CXXBaseSpecifier *&VirtualBaseSpec) {
2242 // First, check for a direct base class.
2243 DirectBaseSpec = 0;
2244 for (CXXRecordDecl::base_class_const_iterator Base
2245 = ClassDecl->bases_begin();
2246 Base != ClassDecl->bases_end(); ++Base) {
2247 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2248 // We found a direct base of this type. That's what we're
2249 // initializing.
2250 DirectBaseSpec = &*Base;
2251 break;
2252 }
2253 }
2254
2255 // Check for a virtual base class.
2256 // FIXME: We might be able to short-circuit this if we know in advance that
2257 // there are no virtual bases.
2258 VirtualBaseSpec = 0;
2259 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2260 // We haven't found a base yet; search the class hierarchy for a
2261 // virtual base class.
2262 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2263 /*DetectVirtual=*/false);
2264 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2265 BaseType, Paths)) {
2266 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2267 Path != Paths.end(); ++Path) {
2268 if (Path->back().Base->isVirtual()) {
2269 VirtualBaseSpec = Path->back().Base;
2270 break;
2271 }
2272 }
2273 }
2274 }
2275
2276 return DirectBaseSpec || VirtualBaseSpec;
2277}
2278
Sebastian Redl6df65482011-09-24 17:48:25 +00002279/// \brief Handle a C++ member initializer using braced-init-list syntax.
2280MemInitResult
2281Sema::ActOnMemInitializer(Decl *ConstructorD,
2282 Scope *S,
2283 CXXScopeSpec &SS,
2284 IdentifierInfo *MemberOrBase,
2285 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002286 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002287 SourceLocation IdLoc,
2288 Expr *InitList,
2289 SourceLocation EllipsisLoc) {
2290 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002291 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002292 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002293}
2294
2295/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002296MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002297Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002298 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002299 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002300 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002301 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002302 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002303 SourceLocation IdLoc,
2304 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002305 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002306 SourceLocation RParenLoc,
2307 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002308 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002309 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002310 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002311 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002312}
2313
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002314namespace {
2315
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002316// Callback to only accept typo corrections that can be a valid C++ member
2317// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002318class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002319public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002320 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2321 : ClassDecl(ClassDecl) {}
2322
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002323 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002324 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2325 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2326 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002327 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002328 }
2329 return false;
2330 }
2331
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002332private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002333 CXXRecordDecl *ClassDecl;
2334};
2335
2336}
2337
Sebastian Redl6df65482011-09-24 17:48:25 +00002338/// \brief Handle a C++ member initializer.
2339MemInitResult
2340Sema::BuildMemInitializer(Decl *ConstructorD,
2341 Scope *S,
2342 CXXScopeSpec &SS,
2343 IdentifierInfo *MemberOrBase,
2344 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002345 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002346 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002347 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002348 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002349 if (!ConstructorD)
2350 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002352 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002353
2354 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002355 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002356 if (!Constructor) {
2357 // The user wrote a constructor initializer on a function that is
2358 // not a C++ constructor. Ignore the error for now, because we may
2359 // have more member initializers coming; we'll diagnose it just
2360 // once in ActOnMemInitializers.
2361 return true;
2362 }
2363
2364 CXXRecordDecl *ClassDecl = Constructor->getParent();
2365
2366 // C++ [class.base.init]p2:
2367 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002368 // constructor's class and, if not found in that scope, are looked
2369 // up in the scope containing the constructor's definition.
2370 // [Note: if the constructor's class contains a member with the
2371 // same name as a direct or virtual base class of the class, a
2372 // mem-initializer-id naming the member or base class and composed
2373 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002374 // mem-initializer-id for the hidden base class may be specified
2375 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002376 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002377 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002378 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002379 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002380 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002381 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002382 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2383 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002384 if (EllipsisLoc.isValid())
2385 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002386 << MemberOrBase
2387 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002388
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002389 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002390 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002391 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002392 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002393 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002394 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002395 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002396
2397 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002398 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002399 } else if (DS.getTypeSpecType() == TST_decltype) {
2400 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002401 } else {
2402 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2403 LookupParsedName(R, S, &SS);
2404
2405 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2406 if (!TyD) {
2407 if (R.isAmbiguous()) return true;
2408
John McCallfd225442010-04-09 19:01:14 +00002409 // We don't want access-control diagnostics here.
2410 R.suppressDiagnostics();
2411
Douglas Gregor7a886e12010-01-19 06:46:48 +00002412 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2413 bool NotUnknownSpecialization = false;
2414 DeclContext *DC = computeDeclContext(SS, false);
2415 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2416 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2417
2418 if (!NotUnknownSpecialization) {
2419 // When the scope specifier can refer to a member of an unknown
2420 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002421 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2422 SS.getWithLocInContext(Context),
2423 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002424 if (BaseType.isNull())
2425 return true;
2426
Douglas Gregor7a886e12010-01-19 06:46:48 +00002427 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002428 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002429 }
2430 }
2431
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002432 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002433 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002434 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002435 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002436 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002437 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002438 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002439 // We have found a non-static data member with a similar
2440 // name to what was typed; complain and initialize that
2441 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002442 diagnoseTypo(Corr,
2443 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2444 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002445 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002446 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002447 const CXXBaseSpecifier *DirectBaseSpec;
2448 const CXXBaseSpecifier *VirtualBaseSpec;
2449 if (FindBaseInitializer(*this, ClassDecl,
2450 Context.getTypeDeclType(Type),
2451 DirectBaseSpec, VirtualBaseSpec)) {
2452 // We have found a direct or virtual base class with a
2453 // similar name to what was typed; complain and initialize
2454 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002455 diagnoseTypo(Corr,
2456 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2457 << MemberOrBase << false,
2458 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002459
Richard Smith2d670972013-08-17 00:46:16 +00002460 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2461 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002462 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002463 diag::note_base_class_specified_here)
2464 << BaseSpec->getType()
2465 << BaseSpec->getSourceRange();
2466
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002467 TyD = Type;
2468 }
2469 }
2470 }
2471
Douglas Gregor7a886e12010-01-19 06:46:48 +00002472 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002473 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002474 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002475 return true;
2476 }
John McCall2b194412009-12-21 10:41:20 +00002477 }
2478
Douglas Gregor7a886e12010-01-19 06:46:48 +00002479 if (BaseType.isNull()) {
2480 BaseType = Context.getTypeDeclType(TyD);
2481 if (SS.isSet()) {
2482 NestedNameSpecifier *Qualifier =
2483 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002484
Douglas Gregor7a886e12010-01-19 06:46:48 +00002485 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002486 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002487 }
John McCall2b194412009-12-21 10:41:20 +00002488 }
2489 }
Mike Stump1eb44332009-09-09 15:08:12 +00002490
John McCalla93c9342009-12-07 02:54:59 +00002491 if (!TInfo)
2492 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002493
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002494 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002495}
2496
Chandler Carruth81c64772011-09-03 01:14:15 +00002497/// Checks a member initializer expression for cases where reference (or
2498/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002499static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2500 Expr *Init,
2501 SourceLocation IdLoc) {
2502 QualType MemberTy = Member->getType();
2503
2504 // We only handle pointers and references currently.
2505 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2506 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2507 return;
2508
2509 const bool IsPointer = MemberTy->isPointerType();
2510 if (IsPointer) {
2511 if (const UnaryOperator *Op
2512 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2513 // The only case we're worried about with pointers requires taking the
2514 // address.
2515 if (Op->getOpcode() != UO_AddrOf)
2516 return;
2517
2518 Init = Op->getSubExpr();
2519 } else {
2520 // We only handle address-of expression initializers for pointers.
2521 return;
2522 }
2523 }
2524
Richard Smitha4bb99c2013-06-12 21:51:50 +00002525 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002526 // We only warn when referring to a non-reference parameter declaration.
2527 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2528 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002529 return;
2530
2531 S.Diag(Init->getExprLoc(),
2532 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2533 : diag::warn_bind_ref_member_to_parameter)
2534 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002535 } else {
2536 // Other initializers are fine.
2537 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002538 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002539
2540 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2541 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002542}
2543
John McCallf312b1e2010-08-26 23:41:50 +00002544MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002545Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002546 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002547 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2548 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2549 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002550 "Member must be a FieldDecl or IndirectFieldDecl");
2551
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002552 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002553 return true;
2554
Douglas Gregor464b2f02010-11-05 22:21:31 +00002555 if (Member->isInvalidDecl())
2556 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002557
John McCallb4190042009-11-04 23:02:40 +00002558 // Diagnose value-uses of fields to initialize themselves, e.g.
2559 // foo(foo)
2560 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002561 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002562 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002563 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002564 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002565 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002566 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002567 } else {
2568 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002569 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002570 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002571
Richard Trieude5e75c2012-06-14 23:11:34 +00002572 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2573 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002574 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002575 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002576 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002577 // initializing the i'th field, throw a warning if any of the >= i'th
2578 // fields are used, as they are not yet initialized.
2579 // Right now we are only handling the case where the i'th field uses
2580 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002581 // Also need to take into account that some fields may be initialized by
2582 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002583 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002584
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002585 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002586
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002587 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002588 // Can't check initialization for a member of dependent type or when
2589 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002590 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002591 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002592 bool InitList = false;
2593 if (isa<InitListExpr>(Init)) {
2594 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002595 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002596 }
2597
Chandler Carruth894aed92010-12-06 09:23:57 +00002598 // Initialize the member.
2599 InitializedEntity MemberEntity =
2600 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2601 : InitializedEntity::InitializeMember(IndirectMember, 0);
2602 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002603 InitList ? InitializationKind::CreateDirectList(IdLoc)
2604 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2605 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002606
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002607 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2608 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002609 if (MemberInit.isInvalid())
2610 return true;
2611
Richard Smith8a07cd32013-06-12 20:42:33 +00002612 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2613
Richard Smith41956372013-01-14 22:39:08 +00002614 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002615 // The initialization of each base and member constitutes a
2616 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002617 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002618 if (MemberInit.isInvalid())
2619 return true;
2620
Richard Smithc83c2302012-12-19 01:39:02 +00002621 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002622 }
2623
Chandler Carruth894aed92010-12-06 09:23:57 +00002624 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002625 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2626 InitRange.getBegin(), Init,
2627 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002628 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002629 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2630 InitRange.getBegin(), Init,
2631 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002632 }
Eli Friedman59c04372009-07-29 19:44:27 +00002633}
2634
John McCallf312b1e2010-08-26 23:41:50 +00002635MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002636Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002637 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002638 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002639 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002640 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002641 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002642 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002643
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002644 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002645 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002646 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2647 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002648 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002649 }
2650
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002651 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002652 // Initialize the object.
2653 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2654 QualType(ClassDecl->getTypeForDecl(), 0));
2655 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002656 InitList ? InitializationKind::CreateDirectList(NameLoc)
2657 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2658 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002659 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002660 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002661 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002662 if (DelegationInit.isInvalid())
2663 return true;
2664
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002665 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2666 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002667
Richard Smith41956372013-01-14 22:39:08 +00002668 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002669 // The initialization of each base and member constitutes a
2670 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002671 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2672 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002673 if (DelegationInit.isInvalid())
2674 return true;
2675
Eli Friedmand21016f2012-05-19 23:35:23 +00002676 // If we are in a dependent context, template instantiation will
2677 // perform this type-checking again. Just save the arguments that we
2678 // received in a ParenListExpr.
2679 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2680 // of the information that we have about the base
2681 // initializer. However, deconstructing the ASTs is a dicey process,
2682 // and this approach is far more likely to get the corner cases right.
2683 if (CurContext->isDependentContext())
2684 DelegationInit = Owned(Init);
2685
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002686 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002687 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002688 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002689}
2690
2691MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002692Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002693 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002694 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002695 SourceLocation BaseLoc
2696 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002697
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002698 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2699 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2700 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2701
2702 // C++ [class.base.init]p2:
2703 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002704 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002705 // of that class, the mem-initializer is ill-formed. A
2706 // mem-initializer-list can initialize a base class using any
2707 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002708 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002709
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002710 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002711 if (EllipsisLoc.isValid()) {
2712 // This is a pack expansion.
2713 if (!BaseType->containsUnexpandedParameterPack()) {
2714 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002715 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002716
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002717 EllipsisLoc = SourceLocation();
2718 }
2719 } else {
2720 // Check for any unexpanded parameter packs.
2721 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2722 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002723
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002724 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002725 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002726 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002727
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002728 // Check for direct and virtual base classes.
2729 const CXXBaseSpecifier *DirectBaseSpec = 0;
2730 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2731 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002732 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2733 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002734 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002735
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002736 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2737 VirtualBaseSpec);
2738
2739 // C++ [base.class.init]p2:
2740 // Unless the mem-initializer-id names a nonstatic data member of the
2741 // constructor's class or a direct or virtual base of that class, the
2742 // mem-initializer is ill-formed.
2743 if (!DirectBaseSpec && !VirtualBaseSpec) {
2744 // If the class has any dependent bases, then it's possible that
2745 // one of those types will resolve to the same type as
2746 // BaseType. Therefore, just treat this as a dependent base
2747 // class initialization. FIXME: Should we try to check the
2748 // initialization anyway? It seems odd.
2749 if (ClassDecl->hasAnyDependentBases())
2750 Dependent = true;
2751 else
2752 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2753 << BaseType << Context.getTypeDeclType(ClassDecl)
2754 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2755 }
2756 }
2757
2758 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002759 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Sebastian Redl6df65482011-09-24 17:48:25 +00002761 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2762 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002763 InitRange.getBegin(), Init,
2764 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002765 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002766
2767 // C++ [base.class.init]p2:
2768 // If a mem-initializer-id is ambiguous because it designates both
2769 // a direct non-virtual base class and an inherited virtual base
2770 // class, the mem-initializer is ill-formed.
2771 if (DirectBaseSpec && VirtualBaseSpec)
2772 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002773 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002774
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002775 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002776 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002777 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002778
2779 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002780 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002781 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002782 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002783 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002784 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002785 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002786
2787 InitializedEntity BaseEntity =
2788 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2789 InitializationKind Kind =
2790 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2791 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2792 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002793 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2794 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002795 if (BaseInit.isInvalid())
2796 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002797
Richard Smith41956372013-01-14 22:39:08 +00002798 // C++11 [class.base.init]p7:
2799 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002800 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002801 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002802 if (BaseInit.isInvalid())
2803 return true;
2804
2805 // If we are in a dependent context, template instantiation will
2806 // perform this type-checking again. Just save the arguments that we
2807 // received in a ParenListExpr.
2808 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2809 // of the information that we have about the base
2810 // initializer. However, deconstructing the ASTs is a dicey process,
2811 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002812 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002813 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002814
Sean Huntcbb67482011-01-08 20:30:50 +00002815 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002816 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002817 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002818 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002819 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002820}
2821
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002822// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002823static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2824 if (T.isNull()) T = E->getType();
2825 QualType TargetType = SemaRef.BuildReferenceType(
2826 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002827 SourceLocation ExprLoc = E->getLocStart();
2828 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2829 TargetType, ExprLoc);
2830
2831 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2832 SourceRange(ExprLoc, ExprLoc),
2833 E->getSourceRange()).take();
2834}
2835
Anders Carlssone5ef7402010-04-23 03:10:23 +00002836/// ImplicitInitializerKind - How an implicit base or member initializer should
2837/// initialize its base or member.
2838enum ImplicitInitializerKind {
2839 IIK_Default,
2840 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002841 IIK_Move,
2842 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002843};
2844
Anders Carlssondefefd22010-04-23 02:00:02 +00002845static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002846BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002847 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002848 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002849 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002850 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002851 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002852 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2853 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002854
John McCall60d7b3a2010-08-24 06:29:42 +00002855 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002856
2857 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002858 case IIK_Inherit: {
2859 const CXXRecordDecl *Inherited =
2860 Constructor->getInheritedConstructor()->getParent();
2861 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2862 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2863 // C++11 [class.inhctor]p8:
2864 // Each expression in the expression-list is of the form
2865 // static_cast<T&&>(p), where p is the name of the corresponding
2866 // constructor parameter and T is the declared type of p.
2867 SmallVector<Expr*, 16> Args;
2868 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2869 ParmVarDecl *PD = Constructor->getParamDecl(I);
2870 ExprResult ArgExpr =
2871 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2872 VK_LValue, SourceLocation());
2873 if (ArgExpr.isInvalid())
2874 return true;
2875 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2876 }
2877
2878 InitializationKind InitKind = InitializationKind::CreateDirect(
2879 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002880 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002881 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2882 break;
2883 }
2884 }
2885 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002886 case IIK_Default: {
2887 InitializationKind InitKind
2888 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002889 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2890 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002891 break;
2892 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002893
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002894 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002895 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002896 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002897 ParmVarDecl *Param = Constructor->getParamDecl(0);
2898 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002899
Anders Carlssone5ef7402010-04-23 03:10:23 +00002900 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002901 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002902 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002903 Constructor->getLocation(), ParamType,
2904 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002905
Eli Friedman5f2987c2012-02-02 03:46:19 +00002906 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2907
Anders Carlssonc7957502010-04-24 22:02:54 +00002908 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002909 QualType ArgTy =
2910 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2911 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002912
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002913 if (Moving) {
2914 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2915 }
2916
John McCallf871d0c2010-08-07 06:22:56 +00002917 CXXCastPath BasePath;
2918 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002919 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2920 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002921 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002922 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002923
Anders Carlssone5ef7402010-04-23 03:10:23 +00002924 InitializationKind InitKind
2925 = InitializationKind::CreateDirect(Constructor->getLocation(),
2926 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002927 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2928 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002929 break;
2930 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002931 }
John McCall9ae2f072010-08-23 23:25:46 +00002932
Douglas Gregor53c374f2010-12-07 00:41:46 +00002933 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002934 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002935 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002936
Anders Carlssondefefd22010-04-23 02:00:02 +00002937 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002938 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002939 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2940 SourceLocation()),
2941 BaseSpec->isVirtual(),
2942 SourceLocation(),
2943 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002944 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002945 SourceLocation());
2946
Anders Carlssondefefd22010-04-23 02:00:02 +00002947 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002948}
2949
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002950static bool RefersToRValueRef(Expr *MemRef) {
2951 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2952 return Referenced->getType()->isRValueReferenceType();
2953}
2954
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002955static bool
2956BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002957 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002958 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002959 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002960 if (Field->isInvalidDecl())
2961 return true;
2962
Chandler Carruthf186b542010-06-29 23:50:44 +00002963 SourceLocation Loc = Constructor->getLocation();
2964
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002965 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2966 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002967 ParmVarDecl *Param = Constructor->getParamDecl(0);
2968 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002969
2970 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002971 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2972 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002973
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002974 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002975 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002976 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002977 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002978
Eli Friedman5f2987c2012-02-02 03:46:19 +00002979 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2980
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002981 if (Moving) {
2982 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2983 }
2984
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002985 // Build a reference to this field within the parameter.
2986 CXXScopeSpec SS;
2987 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2988 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002989 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2990 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002991 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002992 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002993 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002994 ParamType, Loc,
2995 /*IsArrow=*/false,
2996 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002997 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002998 /*FirstQualifierInScope=*/0,
2999 MemberLookup,
3000 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003001 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003002 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003003
3004 // C++11 [class.copy]p15:
3005 // - if a member m has rvalue reference type T&&, it is direct-initialized
3006 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003007 if (RefersToRValueRef(CtorArg.get())) {
3008 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003009 }
3010
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003011 // When the field we are copying is an array, create index variables for
3012 // each dimension of the array. We use these index variables to subscript
3013 // the source array, and other clients (e.g., CodeGen) will perform the
3014 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003015 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003016 QualType BaseType = Field->getType();
3017 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003018 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003019 while (const ConstantArrayType *Array
3020 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003021 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003022 // Create the iteration variable for this array index.
3023 IdentifierInfo *IterationVarName = 0;
3024 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003025 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003026 llvm::raw_svector_ostream OS(Str);
3027 OS << "__i" << IndexVariables.size();
3028 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3029 }
3030 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003031 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003032 IterationVarName, SizeType,
3033 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003034 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003035 IndexVariables.push_back(IterationVar);
3036
3037 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003038 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003039 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003040 assert(!IterationVarRef.isInvalid() &&
3041 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003042 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3043 assert(!IterationVarRef.isInvalid() &&
3044 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003045
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003046 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003047 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003048 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003049 Loc);
3050 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003051 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003052
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003053 BaseType = Array->getElementType();
3054 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003055
3056 // The array subscript expression is an lvalue, which is wrong for moving.
3057 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003058 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003059
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003060 // Construct the entity that we will be initializing. For an array, this
3061 // will be first element in the array, which may require several levels
3062 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003063 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003064 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003065 if (Indirect)
3066 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3067 else
3068 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003069 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3070 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3071 0,
3072 Entities.back()));
3073
3074 // Direct-initialize to use the copy constructor.
3075 InitializationKind InitKind =
3076 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3077
Sebastian Redl74e611a2011-09-04 18:14:28 +00003078 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003079 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003080
John McCall60d7b3a2010-08-24 06:29:42 +00003081 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003082 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003083 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003084 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003085 if (MemberInit.isInvalid())
3086 return true;
3087
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003088 if (Indirect) {
3089 assert(IndexVariables.size() == 0 &&
3090 "Indirect field improperly initialized");
3091 CXXMemberInit
3092 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3093 Loc, Loc,
3094 MemberInit.takeAs<Expr>(),
3095 Loc);
3096 } else
3097 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3098 Loc, MemberInit.takeAs<Expr>(),
3099 Loc,
3100 IndexVariables.data(),
3101 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003102 return false;
3103 }
3104
Richard Smith07b0fdc2013-03-18 21:12:30 +00003105 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3106 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003107
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003108 QualType FieldBaseElementType =
3109 SemaRef.Context.getBaseElementType(Field->getType());
3110
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003111 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003112 InitializedEntity InitEntity
3113 = Indirect? InitializedEntity::InitializeMember(Indirect)
3114 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003115 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003116 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003117
3118 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3119 ExprResult MemberInit =
3120 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003121
Douglas Gregor53c374f2010-12-07 00:41:46 +00003122 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003123 if (MemberInit.isInvalid())
3124 return true;
3125
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003126 if (Indirect)
3127 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3128 Indirect, Loc,
3129 Loc,
3130 MemberInit.get(),
3131 Loc);
3132 else
3133 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3134 Field, Loc, Loc,
3135 MemberInit.get(),
3136 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003137 return false;
3138 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003139
Sean Hunt1f2f3842011-05-17 00:19:05 +00003140 if (!Field->getParent()->isUnion()) {
3141 if (FieldBaseElementType->isReferenceType()) {
3142 SemaRef.Diag(Constructor->getLocation(),
3143 diag::err_uninitialized_member_in_ctor)
3144 << (int)Constructor->isImplicit()
3145 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3146 << 0 << Field->getDeclName();
3147 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3148 return true;
3149 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003150
Sean Hunt1f2f3842011-05-17 00:19:05 +00003151 if (FieldBaseElementType.isConstQualified()) {
3152 SemaRef.Diag(Constructor->getLocation(),
3153 diag::err_uninitialized_member_in_ctor)
3154 << (int)Constructor->isImplicit()
3155 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3156 << 1 << Field->getDeclName();
3157 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3158 return true;
3159 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003160 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003161
David Blaikie4e4d0842012-03-11 07:00:24 +00003162 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003163 FieldBaseElementType->isObjCRetainableType() &&
3164 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3165 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003166 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003167 // Default-initialize Objective-C pointers to NULL.
3168 CXXMemberInit
3169 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3170 Loc, Loc,
3171 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3172 Loc);
3173 return false;
3174 }
3175
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003176 // Nothing to initialize.
3177 CXXMemberInit = 0;
3178 return false;
3179}
John McCallf1860e52010-05-20 23:23:51 +00003180
3181namespace {
3182struct BaseAndFieldInfo {
3183 Sema &S;
3184 CXXConstructorDecl *Ctor;
3185 bool AnyErrorsInInits;
3186 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003187 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003188 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003189
3190 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3191 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003192 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3193 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003194 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003195 else if (Generated && Ctor->isMoveConstructor())
3196 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003197 else if (Ctor->getInheritedConstructor())
3198 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003199 else
3200 IIK = IIK_Default;
3201 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003202
3203 bool isImplicitCopyOrMove() const {
3204 switch (IIK) {
3205 case IIK_Copy:
3206 case IIK_Move:
3207 return true;
3208
3209 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003210 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003211 return false;
3212 }
David Blaikie30263482012-01-20 21:50:17 +00003213
3214 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003215 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003216
3217 bool addFieldInitializer(CXXCtorInitializer *Init) {
3218 AllToInit.push_back(Init);
3219
3220 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003221 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003222 S.UnusedPrivateFields.remove(Init->getAnyMember());
3223
3224 return false;
3225 }
John McCallf1860e52010-05-20 23:23:51 +00003226};
3227}
3228
Richard Smitha4950662011-09-19 13:34:43 +00003229/// \brief Determine whether the given indirect field declaration is somewhere
3230/// within an anonymous union.
3231static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3232 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3233 CEnd = F->chain_end();
3234 C != CEnd; ++C)
3235 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3236 if (Record->isUnion())
3237 return true;
3238
3239 return false;
3240}
3241
Douglas Gregorddb21472011-11-02 23:04:16 +00003242/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3243/// array type.
3244static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3245 if (T->isIncompleteArrayType())
3246 return true;
3247
3248 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3249 if (!ArrayT->getSize())
3250 return true;
3251
3252 T = ArrayT->getElementType();
3253 }
3254
3255 return false;
3256}
3257
Richard Smith7a614d82011-06-11 17:19:42 +00003258static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003259 FieldDecl *Field,
3260 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003261 if (Field->isInvalidDecl())
3262 return false;
John McCallf1860e52010-05-20 23:23:51 +00003263
Chandler Carruthe861c602010-06-30 02:59:29 +00003264 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003265 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3266 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003267
Richard Smith0b8220a2012-08-07 21:30:42 +00003268 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003269 // has a brace-or-equal-initializer, the entity is initialized as specified
3270 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003271 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003272 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3273 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003274 CXXCtorInitializer *Init;
3275 if (Indirect)
3276 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3277 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003278 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003279 SourceLocation());
3280 else
3281 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3282 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003283 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003284 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003285 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003286 }
3287
Richard Smithc115f632011-09-18 11:14:50 +00003288 // Don't build an implicit initializer for union members if none was
3289 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003290 if (Field->getParent()->isUnion() ||
3291 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003292 return false;
3293
Douglas Gregorddb21472011-11-02 23:04:16 +00003294 // Don't initialize incomplete or zero-length arrays.
3295 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3296 return false;
3297
John McCallf1860e52010-05-20 23:23:51 +00003298 // Don't try to build an implicit initializer if there were semantic
3299 // errors in any of the initializers (and therefore we might be
3300 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003301 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003302 return false;
3303
Sean Huntcbb67482011-01-08 20:30:50 +00003304 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003305 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3306 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003307 return true;
John McCallf1860e52010-05-20 23:23:51 +00003308
Richard Smith0b8220a2012-08-07 21:30:42 +00003309 if (!Init)
3310 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003311
Richard Smith0b8220a2012-08-07 21:30:42 +00003312 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003313}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003314
3315bool
3316Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3317 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003318 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003319 Constructor->setNumCtorInitializers(1);
3320 CXXCtorInitializer **initializer =
3321 new (Context) CXXCtorInitializer*[1];
3322 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3323 Constructor->setCtorInitializers(initializer);
3324
Sean Huntb76af9c2011-05-03 23:05:34 +00003325 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003326 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003327 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3328 }
3329
Sean Huntc1598702011-05-05 00:05:47 +00003330 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003331
Sean Hunt059ce0d2011-05-01 07:04:31 +00003332 return false;
3333}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003334
David Blaikie93c86172013-01-17 05:26:25 +00003335bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3336 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003337 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003338 // Just store the initializers as written, they will be checked during
3339 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003340 if (!Initializers.empty()) {
3341 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003342 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003343 new (Context) CXXCtorInitializer*[Initializers.size()];
3344 memcpy(baseOrMemberInitializers, Initializers.data(),
3345 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003346 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003347 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003348
3349 // Let template instantiation know whether we had errors.
3350 if (AnyErrors)
3351 Constructor->setInvalidDecl();
3352
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003353 return false;
3354 }
3355
John McCallf1860e52010-05-20 23:23:51 +00003356 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003357
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003358 // We need to build the initializer AST according to order of construction
3359 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003360 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003361 if (!ClassDecl)
3362 return true;
3363
Eli Friedman80c30da2009-11-09 19:20:36 +00003364 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003365
David Blaikie93c86172013-01-17 05:26:25 +00003366 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003367 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003368
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003369 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003370 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003371 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003372 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003373 }
3374
Anders Carlsson711f34a2010-04-21 19:52:01 +00003375 // Keep track of the direct virtual bases.
3376 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3377 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3378 E = ClassDecl->bases_end(); I != E; ++I) {
3379 if (I->isVirtual())
3380 DirectVBases.insert(I);
3381 }
3382
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003383 // Push virtual bases before others.
3384 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3385 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3386
Sean Huntcbb67482011-01-08 20:30:50 +00003387 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003388 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003389 // [class.base.init]p7, per DR257:
3390 // A mem-initializer where the mem-initializer-id names a virtual base
3391 // class is ignored during execution of a constructor of any class that
3392 // is not the most derived class.
3393 if (ClassDecl->isAbstract()) {
3394 // FIXME: Provide a fixit to remove the base specifier. This requires
3395 // tracking the location of the associated comma for a base specifier.
3396 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3397 << VBase->getType() << ClassDecl;
3398 DiagnoseAbstractType(ClassDecl);
3399 }
3400
John McCallf1860e52010-05-20 23:23:51 +00003401 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003402 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3403 // [class.base.init]p8, per DR257:
3404 // If a given [...] base class is not named by a mem-initializer-id
3405 // [...] and the entity is not a virtual base class of an abstract
3406 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003407 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003408 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003409 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003410 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003411 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003412 HadError = true;
3413 continue;
3414 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003415
John McCallf1860e52010-05-20 23:23:51 +00003416 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003417 }
3418 }
Mike Stump1eb44332009-09-09 15:08:12 +00003419
John McCallf1860e52010-05-20 23:23:51 +00003420 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003421 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3422 E = ClassDecl->bases_end(); Base != E; ++Base) {
3423 // Virtuals are in the virtual base list and already constructed.
3424 if (Base->isVirtual())
3425 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Sean Huntcbb67482011-01-08 20:30:50 +00003427 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003428 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3429 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003430 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003431 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003432 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003433 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003434 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003435 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003436 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003437 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003438
John McCallf1860e52010-05-20 23:23:51 +00003439 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003440 }
3441 }
Mike Stump1eb44332009-09-09 15:08:12 +00003442
John McCallf1860e52010-05-20 23:23:51 +00003443 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003444 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3445 MemEnd = ClassDecl->decls_end();
3446 Mem != MemEnd; ++Mem) {
3447 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003448 // C++ [class.bit]p2:
3449 // A declaration for a bit-field that omits the identifier declares an
3450 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3451 // initialized.
3452 if (F->isUnnamedBitfield())
3453 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003454
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003455 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003456 // handle anonymous struct/union fields based on their individual
3457 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003458 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003459 continue;
3460
3461 if (CollectFieldInitializer(*this, Info, F))
3462 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003463 continue;
3464 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003465
3466 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003467 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003468 continue;
3469
3470 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3471 if (F->getType()->isIncompleteArrayType()) {
3472 assert(ClassDecl->hasFlexibleArrayMember() &&
3473 "Incomplete array type is not valid");
3474 continue;
3475 }
3476
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003477 // Initialize each field of an anonymous struct individually.
3478 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3479 HadError = true;
3480
3481 continue;
3482 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003483 }
Mike Stump1eb44332009-09-09 15:08:12 +00003484
David Blaikie93c86172013-01-17 05:26:25 +00003485 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003486 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003487 Constructor->setNumCtorInitializers(NumInitializers);
3488 CXXCtorInitializer **baseOrMemberInitializers =
3489 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003490 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003491 NumInitializers * sizeof(CXXCtorInitializer*));
3492 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003493
John McCallef027fe2010-03-16 21:39:52 +00003494 // Constructors implicitly reference the base and member
3495 // destructors.
3496 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3497 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003498 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003499
3500 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003501}
3502
David Blaikieee000bb2013-01-17 08:49:22 +00003503static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003504 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003505 const RecordDecl *RD = RT->getDecl();
3506 if (RD->isAnonymousStructOrUnion()) {
3507 for (RecordDecl::field_iterator Field = RD->field_begin(),
3508 E = RD->field_end(); Field != E; ++Field)
3509 PopulateKeysForFields(*Field, IdealInits);
3510 return;
3511 }
Eli Friedman6347f422009-07-21 19:28:10 +00003512 }
David Blaikieee000bb2013-01-17 08:49:22 +00003513 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003514}
3515
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003516static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3517 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003518}
3519
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003520static const void *GetKeyForMember(ASTContext &Context,
3521 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003522 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003523 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003524
David Blaikieee000bb2013-01-17 08:49:22 +00003525 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003526}
3527
David Blaikie93c86172013-01-17 05:26:25 +00003528static void DiagnoseBaseOrMemInitializerOrder(
3529 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3530 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003531 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003532 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003534 // Don't check initializers order unless the warning is enabled at the
3535 // location of at least one initializer.
3536 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003537 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003538 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003539 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3540 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003541 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003542 ShouldCheckOrder = true;
3543 break;
3544 }
3545 }
3546 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003547 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003548
John McCalld6ca8da2010-04-10 07:37:23 +00003549 // Build the list of bases and members in the order that they'll
3550 // actually be initialized. The explicit initializers should be in
3551 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003552 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Anders Carlsson071d6102010-04-02 03:38:04 +00003554 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3555
John McCalld6ca8da2010-04-10 07:37:23 +00003556 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003557 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003558 ClassDecl->vbases_begin(),
3559 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003560 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003561
John McCalld6ca8da2010-04-10 07:37:23 +00003562 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003563 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003564 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003565 if (Base->isVirtual())
3566 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003567 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003568 }
Mike Stump1eb44332009-09-09 15:08:12 +00003569
John McCalld6ca8da2010-04-10 07:37:23 +00003570 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003571 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003572 E = ClassDecl->field_end(); Field != E; ++Field) {
3573 if (Field->isUnnamedBitfield())
3574 continue;
3575
David Blaikieee000bb2013-01-17 08:49:22 +00003576 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003577 }
3578
John McCalld6ca8da2010-04-10 07:37:23 +00003579 unsigned NumIdealInits = IdealInitKeys.size();
3580 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003581
Sean Huntcbb67482011-01-08 20:30:50 +00003582 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003583 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003584 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003585 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003586
3587 // Scan forward to try to find this initializer in the idealized
3588 // initializers list.
3589 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3590 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003591 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003592
3593 // If we didn't find this initializer, it must be because we
3594 // scanned past it on a previous iteration. That can only
3595 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003596 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003597 Sema::SemaDiagnosticBuilder D =
3598 SemaRef.Diag(PrevInit->getSourceLocation(),
3599 diag::warn_initializer_out_of_order);
3600
Francois Pichet00eb3f92010-12-04 09:14:42 +00003601 if (PrevInit->isAnyMemberInitializer())
3602 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003603 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003604 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003605
Francois Pichet00eb3f92010-12-04 09:14:42 +00003606 if (Init->isAnyMemberInitializer())
3607 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003608 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003609 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003610
3611 // Move back to the initializer's location in the ideal list.
3612 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3613 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003614 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003615
3616 assert(IdealIndex != NumIdealInits &&
3617 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003618 }
John McCalld6ca8da2010-04-10 07:37:23 +00003619
3620 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003621 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003622}
3623
John McCall3c3ccdb2010-04-10 09:28:51 +00003624namespace {
3625bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003626 CXXCtorInitializer *Init,
3627 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003628 if (!PrevInit) {
3629 PrevInit = Init;
3630 return false;
3631 }
3632
Douglas Gregordc392c12013-03-25 23:28:23 +00003633 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003634 S.Diag(Init->getSourceLocation(),
3635 diag::err_multiple_mem_initialization)
3636 << Field->getDeclName()
3637 << Init->getSourceRange();
3638 else {
John McCallf4c73712011-01-19 06:33:43 +00003639 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003640 assert(BaseClass && "neither field nor base");
3641 S.Diag(Init->getSourceLocation(),
3642 diag::err_multiple_base_initialization)
3643 << QualType(BaseClass, 0)
3644 << Init->getSourceRange();
3645 }
3646 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3647 << 0 << PrevInit->getSourceRange();
3648
3649 return true;
3650}
3651
Sean Huntcbb67482011-01-08 20:30:50 +00003652typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003653typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3654
3655bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003656 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003657 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003658 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003659 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003660 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003661
3662 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003663 if (Parent->isUnion()) {
3664 UnionEntry &En = Unions[Parent];
3665 if (En.first && En.first != Child) {
3666 S.Diag(Init->getSourceLocation(),
3667 diag::err_multiple_mem_union_initialization)
3668 << Field->getDeclName()
3669 << Init->getSourceRange();
3670 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3671 << 0 << En.second->getSourceRange();
3672 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003673 }
3674 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003675 En.first = Child;
3676 En.second = Init;
3677 }
David Blaikie6fe29652011-11-17 06:01:57 +00003678 if (!Parent->isAnonymousStructOrUnion())
3679 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003680 }
3681
3682 Child = Parent;
3683 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003684 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003685
3686 return false;
3687}
3688}
3689
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003690/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003691void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003692 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003693 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003694 bool AnyErrors) {
3695 if (!ConstructorDecl)
3696 return;
3697
3698 AdjustDeclIfTemplate(ConstructorDecl);
3699
3700 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003701 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003702
3703 if (!Constructor) {
3704 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3705 return;
3706 }
3707
John McCall3c3ccdb2010-04-10 09:28:51 +00003708 // Mapping for the duplicate initializers check.
3709 // For member initializers, this is keyed with a FieldDecl*.
3710 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003711 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003712
3713 // Mapping for the inconsistent anonymous-union initializers check.
3714 RedundantUnionMap MemberUnions;
3715
Anders Carlssonea356fb2010-04-02 05:42:15 +00003716 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003717 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003718 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003719
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003720 // Set the source order index.
3721 Init->setSourceOrder(i);
3722
Francois Pichet00eb3f92010-12-04 09:14:42 +00003723 if (Init->isAnyMemberInitializer()) {
3724 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003725 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3726 CheckRedundantUnionInit(*this, Init, MemberUnions))
3727 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003728 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003729 const void *Key =
3730 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003731 if (CheckRedundantInit(*this, Init, Members[Key]))
3732 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003733 } else {
3734 assert(Init->isDelegatingInitializer());
3735 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003736 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003737 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003738 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003739 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003740 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003741 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003742 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003743 // Return immediately as the initializer is set.
3744 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003745 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003746 }
3747
Anders Carlssonea356fb2010-04-02 05:42:15 +00003748 if (HadError)
3749 return;
3750
David Blaikie93c86172013-01-17 05:26:25 +00003751 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003752
David Blaikie93c86172013-01-17 05:26:25 +00003753 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003754}
3755
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003756void
John McCallef027fe2010-03-16 21:39:52 +00003757Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3758 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003759 // Ignore dependent contexts. Also ignore unions, since their members never
3760 // have destructors implicitly called.
3761 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003762 return;
John McCall58e6f342010-03-16 05:22:47 +00003763
3764 // FIXME: all the access-control diagnostics are positioned on the
3765 // field/base declaration. That's probably good; that said, the
3766 // user might reasonably want to know why the destructor is being
3767 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003768
Anders Carlsson9f853df2009-11-17 04:44:12 +00003769 // Non-static data members.
3770 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3771 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003772 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003773 if (Field->isInvalidDecl())
3774 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003775
3776 // Don't destroy incomplete or zero-length arrays.
3777 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3778 continue;
3779
Anders Carlsson9f853df2009-11-17 04:44:12 +00003780 QualType FieldType = Context.getBaseElementType(Field->getType());
3781
3782 const RecordType* RT = FieldType->getAs<RecordType>();
3783 if (!RT)
3784 continue;
3785
3786 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003787 if (FieldClassDecl->isInvalidDecl())
3788 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003789 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003790 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003791 // The destructor for an implicit anonymous union member is never invoked.
3792 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3793 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003794
Douglas Gregordb89f282010-07-01 22:47:18 +00003795 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003796 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003797 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003798 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003799 << Field->getDeclName()
3800 << FieldType);
3801
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003802 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003803 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003804 }
3805
John McCall58e6f342010-03-16 05:22:47 +00003806 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3807
Anders Carlsson9f853df2009-11-17 04:44:12 +00003808 // Bases.
3809 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3810 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003811 // Bases are always records in a well-formed non-dependent class.
3812 const RecordType *RT = Base->getType()->getAs<RecordType>();
3813
3814 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003815 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003816 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003817
John McCall58e6f342010-03-16 05:22:47 +00003818 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003819 // If our base class is invalid, we probably can't get its dtor anyway.
3820 if (BaseClassDecl->isInvalidDecl())
3821 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003822 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003823 continue;
John McCall58e6f342010-03-16 05:22:47 +00003824
Douglas Gregordb89f282010-07-01 22:47:18 +00003825 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003826 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003827
3828 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003829 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003830 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003831 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003832 << Base->getSourceRange(),
3833 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003834
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003835 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003836 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003837 }
3838
3839 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003840 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3841 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003842
3843 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003844 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003845
3846 // Ignore direct virtual bases.
3847 if (DirectVirtualBases.count(RT))
3848 continue;
3849
John McCall58e6f342010-03-16 05:22:47 +00003850 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003851 // If our base class is invalid, we probably can't get its dtor anyway.
3852 if (BaseClassDecl->isInvalidDecl())
3853 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003854 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003855 continue;
John McCall58e6f342010-03-16 05:22:47 +00003856
Douglas Gregordb89f282010-07-01 22:47:18 +00003857 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003858 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003859 if (CheckDestructorAccess(
3860 ClassDecl->getLocation(), Dtor,
3861 PDiag(diag::err_access_dtor_vbase)
3862 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3863 Context.getTypeDeclType(ClassDecl)) ==
3864 AR_accessible) {
3865 CheckDerivedToBaseConversion(
3866 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3867 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3868 SourceRange(), DeclarationName(), 0);
3869 }
John McCall58e6f342010-03-16 05:22:47 +00003870
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003871 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003872 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003873 }
3874}
3875
John McCalld226f652010-08-21 09:40:31 +00003876void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003877 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003878 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003879
Mike Stump1eb44332009-09-09 15:08:12 +00003880 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003881 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003882 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003883}
3884
Mike Stump1eb44332009-09-09 15:08:12 +00003885bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003886 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003887 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3888 unsigned DiagID;
3889 AbstractDiagSelID SelID;
3890
3891 public:
3892 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3893 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003894
3895 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00003896 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003897 if (SelID == -1)
3898 S.Diag(Loc, DiagID) << T;
3899 else
3900 S.Diag(Loc, DiagID) << SelID << T;
3901 }
3902 } Diagnoser(DiagID, SelID);
3903
3904 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003905}
3906
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003907bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003908 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003909 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003910 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Anders Carlsson11f21a02009-03-23 19:10:31 +00003912 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003913 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Ted Kremenek6217b802009-07-29 21:53:49 +00003915 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003916 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003917 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003918 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003920 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003921 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003922 }
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Ted Kremenek6217b802009-07-29 21:53:49 +00003924 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003925 if (!RT)
3926 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003927
John McCall86ff3082010-02-04 22:26:26 +00003928 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003929
John McCall94c3b562010-08-18 09:41:07 +00003930 // We can't answer whether something is abstract until it has a
3931 // definition. If it's currently being defined, we'll walk back
3932 // over all the declarations when we have a full definition.
3933 const CXXRecordDecl *Def = RD->getDefinition();
3934 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003935 return false;
3936
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003937 if (!RD->isAbstract())
3938 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003940 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003941 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003942
John McCall94c3b562010-08-18 09:41:07 +00003943 return true;
3944}
3945
3946void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3947 // Check if we've already emitted the list of pure virtual functions
3948 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003949 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003950 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003951
Richard Smithcbc820a2013-07-22 02:56:56 +00003952 // If the diagnostic is suppressed, don't emit the notes. We're only
3953 // going to emit them once, so try to attach them to a diagnostic we're
3954 // actually going to show.
3955 if (Diags.isLastDiagnosticIgnored())
3956 return;
3957
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003958 CXXFinalOverriderMap FinalOverriders;
3959 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003961 // Keep a set of seen pure methods so we won't diagnose the same method
3962 // more than once.
3963 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3964
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003965 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3966 MEnd = FinalOverriders.end();
3967 M != MEnd;
3968 ++M) {
3969 for (OverridingMethods::iterator SO = M->second.begin(),
3970 SOEnd = M->second.end();
3971 SO != SOEnd; ++SO) {
3972 // C++ [class.abstract]p4:
3973 // A class is abstract if it contains or inherits at least one
3974 // pure virtual function for which the final overrider is pure
3975 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003977 //
3978 if (SO->second.size() != 1)
3979 continue;
3980
3981 if (!SO->second.front().Method->isPure())
3982 continue;
3983
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003984 if (!SeenPureMethods.insert(SO->second.front().Method))
3985 continue;
3986
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003987 Diag(SO->second.front().Method->getLocation(),
3988 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003989 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003990 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003991 }
3992
3993 if (!PureVirtualClassDiagSet)
3994 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3995 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003996}
3997
Anders Carlsson8211eff2009-03-24 01:19:16 +00003998namespace {
John McCall94c3b562010-08-18 09:41:07 +00003999struct AbstractUsageInfo {
4000 Sema &S;
4001 CXXRecordDecl *Record;
4002 CanQualType AbstractType;
4003 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004004
John McCall94c3b562010-08-18 09:41:07 +00004005 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4006 : S(S), Record(Record),
4007 AbstractType(S.Context.getCanonicalType(
4008 S.Context.getTypeDeclType(Record))),
4009 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004010
John McCall94c3b562010-08-18 09:41:07 +00004011 void DiagnoseAbstractType() {
4012 if (Invalid) return;
4013 S.DiagnoseAbstractType(Record);
4014 Invalid = true;
4015 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004016
John McCall94c3b562010-08-18 09:41:07 +00004017 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4018};
4019
4020struct CheckAbstractUsage {
4021 AbstractUsageInfo &Info;
4022 const NamedDecl *Ctx;
4023
4024 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4025 : Info(Info), Ctx(Ctx) {}
4026
4027 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4028 switch (TL.getTypeLocClass()) {
4029#define ABSTRACT_TYPELOC(CLASS, PARENT)
4030#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004031 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004032#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004033 }
John McCall94c3b562010-08-18 09:41:07 +00004034 }
Mike Stump1eb44332009-09-09 15:08:12 +00004035
John McCall94c3b562010-08-18 09:41:07 +00004036 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4037 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4038 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004039 if (!TL.getArg(I))
4040 continue;
4041
John McCall94c3b562010-08-18 09:41:07 +00004042 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4043 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004044 }
John McCall94c3b562010-08-18 09:41:07 +00004045 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004046
John McCall94c3b562010-08-18 09:41:07 +00004047 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4048 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4049 }
Mike Stump1eb44332009-09-09 15:08:12 +00004050
John McCall94c3b562010-08-18 09:41:07 +00004051 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4052 // Visit the type parameters from a permissive context.
4053 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4054 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4055 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4056 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4057 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4058 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004059 }
John McCall94c3b562010-08-18 09:41:07 +00004060 }
Mike Stump1eb44332009-09-09 15:08:12 +00004061
John McCall94c3b562010-08-18 09:41:07 +00004062 // Visit pointee types from a permissive context.
4063#define CheckPolymorphic(Type) \
4064 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4065 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4066 }
4067 CheckPolymorphic(PointerTypeLoc)
4068 CheckPolymorphic(ReferenceTypeLoc)
4069 CheckPolymorphic(MemberPointerTypeLoc)
4070 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004071 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004072
John McCall94c3b562010-08-18 09:41:07 +00004073 /// Handle all the types we haven't given a more specific
4074 /// implementation for above.
4075 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4076 // Every other kind of type that we haven't called out already
4077 // that has an inner type is either (1) sugar or (2) contains that
4078 // inner type in some way as a subobject.
4079 if (TypeLoc Next = TL.getNextTypeLoc())
4080 return Visit(Next, Sel);
4081
4082 // If there's no inner type and we're in a permissive context,
4083 // don't diagnose.
4084 if (Sel == Sema::AbstractNone) return;
4085
4086 // Check whether the type matches the abstract type.
4087 QualType T = TL.getType();
4088 if (T->isArrayType()) {
4089 Sel = Sema::AbstractArrayType;
4090 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004091 }
John McCall94c3b562010-08-18 09:41:07 +00004092 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4093 if (CT != Info.AbstractType) return;
4094
4095 // It matched; do some magic.
4096 if (Sel == Sema::AbstractArrayType) {
4097 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4098 << T << TL.getSourceRange();
4099 } else {
4100 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4101 << Sel << T << TL.getSourceRange();
4102 }
4103 Info.DiagnoseAbstractType();
4104 }
4105};
4106
4107void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4108 Sema::AbstractDiagSelID Sel) {
4109 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4110}
4111
4112}
4113
4114/// Check for invalid uses of an abstract type in a method declaration.
4115static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4116 CXXMethodDecl *MD) {
4117 // No need to do the check on definitions, which require that
4118 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004119 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004120 return;
4121
4122 // For safety's sake, just ignore it if we don't have type source
4123 // information. This should never happen for non-implicit methods,
4124 // but...
4125 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4126 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4127}
4128
4129/// Check for invalid uses of an abstract type within a class definition.
4130static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4131 CXXRecordDecl *RD) {
4132 for (CXXRecordDecl::decl_iterator
4133 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4134 Decl *D = *I;
4135 if (D->isImplicit()) continue;
4136
4137 // Methods and method templates.
4138 if (isa<CXXMethodDecl>(D)) {
4139 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4140 } else if (isa<FunctionTemplateDecl>(D)) {
4141 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4142 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4143
4144 // Fields and static variables.
4145 } else if (isa<FieldDecl>(D)) {
4146 FieldDecl *FD = cast<FieldDecl>(D);
4147 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4148 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4149 } else if (isa<VarDecl>(D)) {
4150 VarDecl *VD = cast<VarDecl>(D);
4151 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4152 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4153
4154 // Nested classes and class templates.
4155 } else if (isa<CXXRecordDecl>(D)) {
4156 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4157 } else if (isa<ClassTemplateDecl>(D)) {
4158 CheckAbstractClassUsage(Info,
4159 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4160 }
4161 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004162}
4163
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004164/// \brief Perform semantic checks on a class definition that has been
4165/// completing, introducing implicitly-declared members, checking for
4166/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004167void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004168 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004169 return;
4170
John McCall94c3b562010-08-18 09:41:07 +00004171 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4172 AbstractUsageInfo Info(*this, Record);
4173 CheckAbstractClassUsage(Info, Record);
4174 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004175
4176 // If this is not an aggregate type and has no user-declared constructor,
4177 // complain about any non-static data members of reference or const scalar
4178 // type, since they will never get initializers.
4179 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004180 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4181 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004182 bool Complained = false;
4183 for (RecordDecl::field_iterator F = Record->field_begin(),
4184 FEnd = Record->field_end();
4185 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004186 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004187 continue;
4188
Douglas Gregor325e5932010-04-15 00:00:53 +00004189 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004190 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004191 if (!Complained) {
4192 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4193 << Record->getTagKind() << Record;
4194 Complained = true;
4195 }
4196
4197 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4198 << F->getType()->isReferenceType()
4199 << F->getDeclName();
4200 }
4201 }
4202 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004203
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004204 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004205 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004206
4207 if (Record->getIdentifier()) {
4208 // C++ [class.mem]p13:
4209 // If T is the name of a class, then each of the following shall have a
4210 // name different from T:
4211 // - every member of every anonymous union that is a member of class T.
4212 //
4213 // C++ [class.mem]p14:
4214 // In addition, if class T has a user-declared constructor (12.1), every
4215 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004216 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4217 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4218 ++I) {
4219 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004220 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4221 isa<IndirectFieldDecl>(D)) {
4222 Diag(D->getLocation(), diag::err_member_name_of_class)
4223 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004224 break;
4225 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004226 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004227 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004228
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004229 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004230 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004231 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004232 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004233 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4234 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4235 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004236
David Blaikieb6b5b972012-09-21 03:21:07 +00004237 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4238 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4239 DiagnoseAbstractType(Record);
4240 }
4241
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004242 if (!Record->isDependentType()) {
4243 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4244 MEnd = Record->method_end();
4245 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004246 // See if a method overloads virtual methods in a base
4247 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004248 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004249 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004250
4251 // Check whether the explicitly-defaulted special members are valid.
4252 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4253 CheckExplicitlyDefaultedSpecialMember(*M);
4254
4255 // For an explicitly defaulted or deleted special member, we defer
4256 // determining triviality until the class is complete. That time is now!
4257 if (!M->isImplicit() && !M->isUserProvided()) {
4258 CXXSpecialMember CSM = getSpecialMember(*M);
4259 if (CSM != CXXInvalid) {
4260 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4261
4262 // Inform the class that we've finished declaring this member.
4263 Record->finishedDefaultedOrDeletedMember(*M);
4264 }
4265 }
4266 }
4267 }
4268
4269 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4270 // function that is not a constructor declares that member function to be
4271 // const. [...] The class of which that function is a member shall be
4272 // a literal type.
4273 //
4274 // If the class has virtual bases, any constexpr members will already have
4275 // been diagnosed by the checks performed on the member declaration, so
4276 // suppress this (less useful) diagnostic.
4277 //
4278 // We delay this until we know whether an explicitly-defaulted (or deleted)
4279 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004280 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004281 !Record->isLiteral() && !Record->getNumVBases()) {
4282 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4283 MEnd = Record->method_end();
4284 M != MEnd; ++M) {
4285 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4286 switch (Record->getTemplateSpecializationKind()) {
4287 case TSK_ImplicitInstantiation:
4288 case TSK_ExplicitInstantiationDeclaration:
4289 case TSK_ExplicitInstantiationDefinition:
4290 // If a template instantiates to a non-literal type, but its members
4291 // instantiate to constexpr functions, the template is technically
4292 // ill-formed, but we allow it for sanity.
4293 continue;
4294
4295 case TSK_Undeclared:
4296 case TSK_ExplicitSpecialization:
4297 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4298 diag::err_constexpr_method_non_literal);
4299 break;
4300 }
4301
4302 // Only produce one error per class.
4303 break;
4304 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004305 }
4306 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004307
Richard Smith07b0fdc2013-03-18 21:12:30 +00004308 // Declare inheriting constructors. We do this eagerly here because:
4309 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004310 // constructors from different classes.
4311 // - The lazy declaration of the other implicit constructors is so as to not
4312 // waste space and performance on classes that are not meant to be
4313 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004314 // have inheriting constructors.
4315 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004316}
4317
Richard Smith7756afa2012-06-10 05:43:50 +00004318/// Is the special member function which would be selected to perform the
4319/// specified operation on the specified class type a constexpr constructor?
4320static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4321 Sema::CXXSpecialMember CSM,
4322 bool ConstArg) {
4323 Sema::SpecialMemberOverloadResult *SMOR =
4324 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4325 false, false, false, false);
4326 if (!SMOR || !SMOR->getMethod())
4327 // A constructor we wouldn't select can't be "involved in initializing"
4328 // anything.
4329 return true;
4330 return SMOR->getMethod()->isConstexpr();
4331}
4332
4333/// Determine whether the specified special member function would be constexpr
4334/// if it were implicitly defined.
4335static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4336 Sema::CXXSpecialMember CSM,
4337 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004338 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004339 return false;
4340
4341 // C++11 [dcl.constexpr]p4:
4342 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004343 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004344 switch (CSM) {
4345 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004346 // Since default constructor lookup is essentially trivial (and cannot
4347 // involve, for instance, template instantiation), we compute whether a
4348 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4349 //
4350 // This is important for performance; we need to know whether the default
4351 // constructor is constexpr to determine whether the type is a literal type.
4352 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4353
Richard Smith7756afa2012-06-10 05:43:50 +00004354 case Sema::CXXCopyConstructor:
4355 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004356 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004357 break;
4358
4359 case Sema::CXXCopyAssignment:
4360 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004361 if (!S.getLangOpts().CPlusPlus1y)
4362 return false;
4363 // In C++1y, we need to perform overload resolution.
4364 Ctor = false;
4365 break;
4366
Richard Smith7756afa2012-06-10 05:43:50 +00004367 case Sema::CXXDestructor:
4368 case Sema::CXXInvalid:
4369 return false;
4370 }
4371
4372 // -- if the class is a non-empty union, or for each non-empty anonymous
4373 // union member of a non-union class, exactly one non-static data member
4374 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004375 //
4376 // If we squint, this is guaranteed, since exactly one non-static data member
4377 // will be initialized (if the constructor isn't deleted), we just don't know
4378 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004379 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004380 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004381
4382 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004383 if (Ctor && ClassDecl->getNumVBases())
4384 return false;
4385
4386 // C++1y [class.copy]p26:
4387 // -- [the class] is a literal type, and
4388 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004389 return false;
4390
4391 // -- every constructor involved in initializing [...] base class
4392 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004393 // -- the assignment operator selected to copy/move each direct base
4394 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004395 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4396 BEnd = ClassDecl->bases_end();
4397 B != BEnd; ++B) {
4398 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4399 if (!BaseType) continue;
4400
4401 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4402 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4403 return false;
4404 }
4405
4406 // -- every constructor involved in initializing non-static data members
4407 // [...] shall be a constexpr constructor;
4408 // -- every non-static data member and base class sub-object shall be
4409 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004410 // -- for each non-stastic data member of X that is of class type (or array
4411 // thereof), the assignment operator selected to copy/move that member is
4412 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004413 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4414 FEnd = ClassDecl->field_end();
4415 F != FEnd; ++F) {
4416 if (F->isInvalidDecl())
4417 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004418 if (const RecordType *RecordTy =
4419 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004420 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4421 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4422 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004423 }
4424 }
4425
4426 // All OK, it's constexpr!
4427 return true;
4428}
4429
Richard Smithb9d0b762012-07-27 04:22:15 +00004430static Sema::ImplicitExceptionSpecification
4431computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4432 switch (S.getSpecialMember(MD)) {
4433 case Sema::CXXDefaultConstructor:
4434 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4435 case Sema::CXXCopyConstructor:
4436 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4437 case Sema::CXXCopyAssignment:
4438 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4439 case Sema::CXXMoveConstructor:
4440 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4441 case Sema::CXXMoveAssignment:
4442 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4443 case Sema::CXXDestructor:
4444 return S.ComputeDefaultedDtorExceptionSpec(MD);
4445 case Sema::CXXInvalid:
4446 break;
4447 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004448 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4449 "only special members have implicit exception specs");
4450 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004451}
4452
Richard Smithdd25e802012-07-30 23:48:14 +00004453static void
4454updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4455 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4456 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4457 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004458 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4459 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004460}
4461
Reid Kleckneref072032013-08-27 23:08:25 +00004462static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4463 CXXMethodDecl *MD) {
4464 FunctionProtoType::ExtProtoInfo EPI;
4465
4466 // Build an exception specification pointing back at this member.
4467 EPI.ExceptionSpecType = EST_Unevaluated;
4468 EPI.ExceptionSpecDecl = MD;
4469
4470 // Set the calling convention to the default for C++ instance methods.
4471 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4472 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4473 /*IsCXXMethod=*/true));
4474 return EPI;
4475}
4476
Richard Smithb9d0b762012-07-27 04:22:15 +00004477void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4478 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4479 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4480 return;
4481
Richard Smithdd25e802012-07-30 23:48:14 +00004482 // Evaluate the exception specification.
4483 ImplicitExceptionSpecification ExceptSpec =
4484 computeImplicitExceptionSpec(*this, Loc, MD);
4485
4486 // Update the type of the special member to use it.
4487 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4488
4489 // A user-provided destructor can be defined outside the class. When that
4490 // happens, be sure to update the exception specification on both
4491 // declarations.
4492 const FunctionProtoType *CanonicalFPT =
4493 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4494 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4495 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4496 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004497}
4498
Richard Smith3003e1d2012-05-15 04:39:51 +00004499void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4500 CXXRecordDecl *RD = MD->getParent();
4501 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004502
Richard Smith3003e1d2012-05-15 04:39:51 +00004503 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4504 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004505
4506 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004507 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004508 bool First = MD == MD->getCanonicalDecl();
4509
4510 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004511
4512 // C++11 [dcl.fct.def.default]p1:
4513 // A function that is explicitly defaulted shall
4514 // -- be a special member function (checked elsewhere),
4515 // -- have the same type (except for ref-qualifiers, and except that a
4516 // copy operation can take a non-const reference) as an implicit
4517 // declaration, and
4518 // -- not have default arguments.
4519 unsigned ExpectedParams = 1;
4520 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4521 ExpectedParams = 0;
4522 if (MD->getNumParams() != ExpectedParams) {
4523 // This also checks for default arguments: a copy or move constructor with a
4524 // default argument is classified as a default constructor, and assignment
4525 // operations and destructors can't have default arguments.
4526 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4527 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004528 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004529 } else if (MD->isVariadic()) {
4530 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4531 << CSM << MD->getSourceRange();
4532 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004533 }
4534
Richard Smith3003e1d2012-05-15 04:39:51 +00004535 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004536
Richard Smith7756afa2012-06-10 05:43:50 +00004537 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004538 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004539 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004540 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004541 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004542
Richard Smith3003e1d2012-05-15 04:39:51 +00004543 QualType ReturnType = Context.VoidTy;
4544 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4545 // Check for return type matching.
4546 ReturnType = Type->getResultType();
4547 QualType ExpectedReturnType =
4548 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4549 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4550 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4551 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4552 HadError = true;
4553 }
4554
4555 // A defaulted special member cannot have cv-qualifiers.
4556 if (Type->getTypeQuals()) {
4557 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004558 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004559 HadError = true;
4560 }
4561 }
4562
4563 // Check for parameter type matching.
4564 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004565 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004566 if (ExpectedParams && ArgType->isReferenceType()) {
4567 // Argument must be reference to possibly-const T.
4568 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004569 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004570
4571 if (ReferentType.isVolatileQualified()) {
4572 Diag(MD->getLocation(),
4573 diag::err_defaulted_special_member_volatile_param) << CSM;
4574 HadError = true;
4575 }
4576
Richard Smith7756afa2012-06-10 05:43:50 +00004577 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004578 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4579 Diag(MD->getLocation(),
4580 diag::err_defaulted_special_member_copy_const_param)
4581 << (CSM == CXXCopyAssignment);
4582 // FIXME: Explain why this special member can't be const.
4583 } else {
4584 Diag(MD->getLocation(),
4585 diag::err_defaulted_special_member_move_const_param)
4586 << (CSM == CXXMoveAssignment);
4587 }
4588 HadError = true;
4589 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004590 } else if (ExpectedParams) {
4591 // A copy assignment operator can take its argument by value, but a
4592 // defaulted one cannot.
4593 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004594 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004595 HadError = true;
4596 }
Sean Huntbe631222011-05-17 20:44:43 +00004597
Richard Smith61802452011-12-22 02:22:31 +00004598 // C++11 [dcl.fct.def.default]p2:
4599 // An explicitly-defaulted function may be declared constexpr only if it
4600 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004601 // Do not apply this rule to members of class templates, since core issue 1358
4602 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004603 // functions which cannot be constexpr (for non-constructors in C++11 and for
4604 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004605 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4606 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004607 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4608 : isa<CXXConstructorDecl>(MD)) &&
4609 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004610 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4611 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004612 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004613 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004614 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004615
Richard Smith61802452011-12-22 02:22:31 +00004616 // and may have an explicit exception-specification only if it is compatible
4617 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004618 if (Type->hasExceptionSpec()) {
4619 // Delay the check if this is the first declaration of the special member,
4620 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004621 if (First) {
4622 // If the exception specification needs to be instantiated, do so now,
4623 // before we clobber it with an EST_Unevaluated specification below.
4624 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4625 InstantiateExceptionSpec(MD->getLocStart(), MD);
4626 Type = MD->getType()->getAs<FunctionProtoType>();
4627 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004628 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004629 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004630 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4631 }
Richard Smith61802452011-12-22 02:22:31 +00004632
4633 // If a function is explicitly defaulted on its first declaration,
4634 if (First) {
4635 // -- it is implicitly considered to be constexpr if the implicit
4636 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004637 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004638
Richard Smith3003e1d2012-05-15 04:39:51 +00004639 // -- it is implicitly considered to have the same exception-specification
4640 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004641 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4642 EPI.ExceptionSpecType = EST_Unevaluated;
4643 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004644 MD->setType(Context.getFunctionType(ReturnType,
4645 ArrayRef<QualType>(&ArgType,
4646 ExpectedParams),
4647 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004648 }
4649
Richard Smith3003e1d2012-05-15 04:39:51 +00004650 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004651 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004652 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004653 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004654 // C++11 [dcl.fct.def.default]p4:
4655 // [For a] user-provided explicitly-defaulted function [...] if such a
4656 // function is implicitly defined as deleted, the program is ill-formed.
4657 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4658 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004659 }
4660 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004661
Richard Smith3003e1d2012-05-15 04:39:51 +00004662 if (HadError)
4663 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004664}
4665
Richard Smith1d28caf2012-12-11 01:14:52 +00004666/// Check whether the exception specification provided for an
4667/// explicitly-defaulted special member matches the exception specification
4668/// that would have been generated for an implicit special member, per
4669/// C++11 [dcl.fct.def.default]p2.
4670void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4671 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4672 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004673 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4674 /*IsCXXMethod=*/true);
4675 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004676 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4677 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004678 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004679
4680 // Ensure that it matches.
4681 CheckEquivalentExceptionSpec(
4682 PDiag(diag::err_incorrect_defaulted_exception_spec)
4683 << getSpecialMember(MD), PDiag(),
4684 ImplicitType, SourceLocation(),
4685 SpecifiedType, MD->getLocation());
4686}
4687
4688void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4689 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4690 I != N; ++I)
4691 CheckExplicitlyDefaultedMemberExceptionSpec(
4692 DelayedDefaultedMemberExceptionSpecs[I].first,
4693 DelayedDefaultedMemberExceptionSpecs[I].second);
4694
4695 DelayedDefaultedMemberExceptionSpecs.clear();
4696}
4697
Richard Smith7d5088a2012-02-18 02:02:13 +00004698namespace {
4699struct SpecialMemberDeletionInfo {
4700 Sema &S;
4701 CXXMethodDecl *MD;
4702 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004703 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004704
4705 // Properties of the special member, computed for convenience.
4706 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4707 SourceLocation Loc;
4708
4709 bool AllFieldsAreConst;
4710
4711 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004712 Sema::CXXSpecialMember CSM, bool Diagnose)
4713 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004714 IsConstructor(false), IsAssignment(false), IsMove(false),
4715 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4716 AllFieldsAreConst(true) {
4717 switch (CSM) {
4718 case Sema::CXXDefaultConstructor:
4719 case Sema::CXXCopyConstructor:
4720 IsConstructor = true;
4721 break;
4722 case Sema::CXXMoveConstructor:
4723 IsConstructor = true;
4724 IsMove = true;
4725 break;
4726 case Sema::CXXCopyAssignment:
4727 IsAssignment = true;
4728 break;
4729 case Sema::CXXMoveAssignment:
4730 IsAssignment = true;
4731 IsMove = true;
4732 break;
4733 case Sema::CXXDestructor:
4734 break;
4735 case Sema::CXXInvalid:
4736 llvm_unreachable("invalid special member kind");
4737 }
4738
4739 if (MD->getNumParams()) {
4740 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4741 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4742 }
4743 }
4744
4745 bool inUnion() const { return MD->getParent()->isUnion(); }
4746
4747 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004748 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4749 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004750 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004751 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4752 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4753 Quals = 0;
4754 return S.LookupSpecialMember(Class, CSM,
4755 ConstArg || (Quals & Qualifiers::Const),
4756 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004757 MD->getRefQualifier() == RQ_RValue,
4758 TQ & Qualifiers::Const,
4759 TQ & Qualifiers::Volatile);
4760 }
4761
Richard Smith6c4c36c2012-03-30 20:53:28 +00004762 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004763
Richard Smith6c4c36c2012-03-30 20:53:28 +00004764 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004765 bool shouldDeleteForField(FieldDecl *FD);
4766 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004767
Richard Smith517bb842012-07-18 03:51:16 +00004768 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4769 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004770 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4771 Sema::SpecialMemberOverloadResult *SMOR,
4772 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004773
4774 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004775};
4776}
4777
John McCall12d8d802012-04-09 20:53:23 +00004778/// Is the given special member inaccessible when used on the given
4779/// sub-object.
4780bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4781 CXXMethodDecl *target) {
4782 /// If we're operating on a base class, the object type is the
4783 /// type of this special member.
4784 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004785 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004786 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4787 objectTy = S.Context.getTypeDeclType(MD->getParent());
4788 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4789
4790 // If we're operating on a field, the object type is the type of the field.
4791 } else {
4792 objectTy = S.Context.getTypeDeclType(target->getParent());
4793 }
4794
4795 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4796}
4797
Richard Smith6c4c36c2012-03-30 20:53:28 +00004798/// Check whether we should delete a special member due to the implicit
4799/// definition containing a call to a special member of a subobject.
4800bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4801 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4802 bool IsDtorCallInCtor) {
4803 CXXMethodDecl *Decl = SMOR->getMethod();
4804 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4805
4806 int DiagKind = -1;
4807
4808 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4809 DiagKind = !Decl ? 0 : 1;
4810 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4811 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004812 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004813 DiagKind = 3;
4814 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4815 !Decl->isTrivial()) {
4816 // A member of a union must have a trivial corresponding special member.
4817 // As a weird special case, a destructor call from a union's constructor
4818 // must be accessible and non-deleted, but need not be trivial. Such a
4819 // destructor is never actually called, but is semantically checked as
4820 // if it were.
4821 DiagKind = 4;
4822 }
4823
4824 if (DiagKind == -1)
4825 return false;
4826
4827 if (Diagnose) {
4828 if (Field) {
4829 S.Diag(Field->getLocation(),
4830 diag::note_deleted_special_member_class_subobject)
4831 << CSM << MD->getParent() << /*IsField*/true
4832 << Field << DiagKind << IsDtorCallInCtor;
4833 } else {
4834 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4835 S.Diag(Base->getLocStart(),
4836 diag::note_deleted_special_member_class_subobject)
4837 << CSM << MD->getParent() << /*IsField*/false
4838 << Base->getType() << DiagKind << IsDtorCallInCtor;
4839 }
4840
4841 if (DiagKind == 1)
4842 S.NoteDeletedFunction(Decl);
4843 // FIXME: Explain inaccessibility if DiagKind == 3.
4844 }
4845
4846 return true;
4847}
4848
Richard Smith9a561d52012-02-26 09:11:52 +00004849/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004850/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004851bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004852 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004853 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004854
4855 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004856 // -- any direct or virtual base class, or non-static data member with no
4857 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004858 // either M has no default constructor or overload resolution as applied
4859 // to M's default constructor results in an ambiguity or in a function
4860 // that is deleted or inaccessible
4861 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4862 // -- a direct or virtual base class B that cannot be copied/moved because
4863 // overload resolution, as applied to B's corresponding special member,
4864 // results in an ambiguity or a function that is deleted or inaccessible
4865 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004866 // C++11 [class.dtor]p5:
4867 // -- any direct or virtual base class [...] has a type with a destructor
4868 // that is deleted or inaccessible
4869 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004870 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004871 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004872 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004873
Richard Smith6c4c36c2012-03-30 20:53:28 +00004874 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4875 // -- any direct or virtual base class or non-static data member has a
4876 // type with a destructor that is deleted or inaccessible
4877 if (IsConstructor) {
4878 Sema::SpecialMemberOverloadResult *SMOR =
4879 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4880 false, false, false, false, false);
4881 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4882 return true;
4883 }
4884
Richard Smith9a561d52012-02-26 09:11:52 +00004885 return false;
4886}
4887
4888/// Check whether we should delete a special member function due to the class
4889/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004890bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004891 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004892 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004893}
4894
4895/// Check whether we should delete a special member function due to the class
4896/// having a particular non-static data member.
4897bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4898 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4899 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4900
4901 if (CSM == Sema::CXXDefaultConstructor) {
4902 // For a default constructor, all references must be initialized in-class
4903 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004904 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4905 if (Diagnose)
4906 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4907 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004908 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004909 }
Richard Smith79363f52012-02-27 06:07:25 +00004910 // C++11 [class.ctor]p5: any non-variant non-static data member of
4911 // const-qualified type (or array thereof) with no
4912 // brace-or-equal-initializer does not have a user-provided default
4913 // constructor.
4914 if (!inUnion() && FieldType.isConstQualified() &&
4915 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004916 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4917 if (Diagnose)
4918 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004919 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004920 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004921 }
4922
4923 if (inUnion() && !FieldType.isConstQualified())
4924 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004925 } else if (CSM == Sema::CXXCopyConstructor) {
4926 // For a copy constructor, data members must not be of rvalue reference
4927 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004928 if (FieldType->isRValueReferenceType()) {
4929 if (Diagnose)
4930 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4931 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004932 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004933 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004934 } else if (IsAssignment) {
4935 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004936 if (FieldType->isReferenceType()) {
4937 if (Diagnose)
4938 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4939 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004940 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004941 }
4942 if (!FieldRecord && FieldType.isConstQualified()) {
4943 // C++11 [class.copy]p23:
4944 // -- a non-static data member of const non-class type (or array thereof)
4945 if (Diagnose)
4946 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004947 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004948 return true;
4949 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004950 }
4951
4952 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004953 // Some additional restrictions exist on the variant members.
4954 if (!inUnion() && FieldRecord->isUnion() &&
4955 FieldRecord->isAnonymousStructOrUnion()) {
4956 bool AllVariantFieldsAreConst = true;
4957
Richard Smithdf8dc862012-03-29 19:00:10 +00004958 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004959 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4960 UE = FieldRecord->field_end();
4961 UI != UE; ++UI) {
4962 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004963
4964 if (!UnionFieldType.isConstQualified())
4965 AllVariantFieldsAreConst = false;
4966
Richard Smith9a561d52012-02-26 09:11:52 +00004967 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4968 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004969 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4970 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004971 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004972 }
4973
4974 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004975 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004976 FieldRecord->field_begin() != FieldRecord->field_end()) {
4977 if (Diagnose)
4978 S.Diag(FieldRecord->getLocation(),
4979 diag::note_deleted_default_ctor_all_const)
4980 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004981 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004982 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004983
Richard Smithdf8dc862012-03-29 19:00:10 +00004984 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004985 // This is technically non-conformant, but sanity demands it.
4986 return false;
4987 }
4988
Richard Smith517bb842012-07-18 03:51:16 +00004989 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4990 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004991 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004992 }
4993
4994 return false;
4995}
4996
4997/// C++11 [class.ctor] p5:
4998/// A defaulted default constructor for a class X is defined as deleted if
4999/// X is a union and all of its variant members are of const-qualified type.
5000bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005001 // This is a silly definition, because it gives an empty union a deleted
5002 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005003 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5004 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5005 if (Diagnose)
5006 S.Diag(MD->getParent()->getLocation(),
5007 diag::note_deleted_default_ctor_all_const)
5008 << MD->getParent() << /*not anonymous union*/0;
5009 return true;
5010 }
5011 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005012}
5013
5014/// Determine whether a defaulted special member function should be defined as
5015/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5016/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005017bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5018 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005019 if (MD->isInvalidDecl())
5020 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005021 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005022 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005023 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005024 return false;
5025
Richard Smith7d5088a2012-02-18 02:02:13 +00005026 // C++11 [expr.lambda.prim]p19:
5027 // The closure type associated with a lambda-expression has a
5028 // deleted (8.4.3) default constructor and a deleted copy
5029 // assignment operator.
5030 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005031 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5032 if (Diagnose)
5033 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005034 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005035 }
5036
Richard Smith5bdaac52012-04-02 20:59:25 +00005037 // For an anonymous struct or union, the copy and assignment special members
5038 // will never be used, so skip the check. For an anonymous union declared at
5039 // namespace scope, the constructor and destructor are used.
5040 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5041 RD->isAnonymousStructOrUnion())
5042 return false;
5043
Richard Smith6c4c36c2012-03-30 20:53:28 +00005044 // C++11 [class.copy]p7, p18:
5045 // If the class definition declares a move constructor or move assignment
5046 // operator, an implicitly declared copy constructor or copy assignment
5047 // operator is defined as deleted.
5048 if (MD->isImplicit() &&
5049 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5050 CXXMethodDecl *UserDeclaredMove = 0;
5051
5052 // In Microsoft mode, a user-declared move only causes the deletion of the
5053 // corresponding copy operation, not both copy operations.
5054 if (RD->hasUserDeclaredMoveConstructor() &&
5055 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5056 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005057
5058 // Find any user-declared move constructor.
5059 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5060 E = RD->ctor_end(); I != E; ++I) {
5061 if (I->isMoveConstructor()) {
5062 UserDeclaredMove = *I;
5063 break;
5064 }
5065 }
Richard Smith1c931be2012-04-02 18:40:40 +00005066 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005067 } else if (RD->hasUserDeclaredMoveAssignment() &&
5068 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5069 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005070
5071 // Find any user-declared move assignment operator.
5072 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5073 E = RD->method_end(); I != E; ++I) {
5074 if (I->isMoveAssignmentOperator()) {
5075 UserDeclaredMove = *I;
5076 break;
5077 }
5078 }
Richard Smith1c931be2012-04-02 18:40:40 +00005079 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005080 }
5081
5082 if (UserDeclaredMove) {
5083 Diag(UserDeclaredMove->getLocation(),
5084 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005085 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005086 << UserDeclaredMove->isMoveAssignmentOperator();
5087 return true;
5088 }
5089 }
Sean Hunte16da072011-10-10 06:18:57 +00005090
Richard Smith5bdaac52012-04-02 20:59:25 +00005091 // Do access control from the special member function
5092 ContextRAII MethodContext(*this, MD);
5093
Richard Smith9a561d52012-02-26 09:11:52 +00005094 // C++11 [class.dtor]p5:
5095 // -- for a virtual destructor, lookup of the non-array deallocation function
5096 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005097 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005098 FunctionDecl *OperatorDelete = 0;
5099 DeclarationName Name =
5100 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5101 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005102 OperatorDelete, false)) {
5103 if (Diagnose)
5104 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005105 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005106 }
Richard Smith9a561d52012-02-26 09:11:52 +00005107 }
5108
Richard Smith6c4c36c2012-03-30 20:53:28 +00005109 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005110
Sean Huntcdee3fe2011-05-11 22:34:38 +00005111 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005112 BE = RD->bases_end(); BI != BE; ++BI)
5113 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005114 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005115 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005116
Richard Smithe0883602013-07-22 18:06:23 +00005117 // Per DR1611, do not consider virtual bases of constructors of abstract
5118 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005119 if (!RD->isAbstract() || !SMI.IsConstructor) {
5120 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5121 BE = RD->vbases_end();
5122 BI != BE; ++BI)
5123 if (SMI.shouldDeleteForBase(BI))
5124 return true;
5125 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005126
5127 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005128 FE = RD->field_end(); FI != FE; ++FI)
5129 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005130 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005131 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005132
Richard Smith7d5088a2012-02-18 02:02:13 +00005133 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005134 return true;
5135
5136 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005137}
5138
Richard Smithac713512012-12-08 02:53:02 +00005139/// Perform lookup for a special member of the specified kind, and determine
5140/// whether it is trivial. If the triviality can be determined without the
5141/// lookup, skip it. This is intended for use when determining whether a
5142/// special member of a containing object is trivial, and thus does not ever
5143/// perform overload resolution for default constructors.
5144///
5145/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5146/// member that was most likely to be intended to be trivial, if any.
5147static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5148 Sema::CXXSpecialMember CSM, unsigned Quals,
5149 CXXMethodDecl **Selected) {
5150 if (Selected)
5151 *Selected = 0;
5152
5153 switch (CSM) {
5154 case Sema::CXXInvalid:
5155 llvm_unreachable("not a special member");
5156
5157 case Sema::CXXDefaultConstructor:
5158 // C++11 [class.ctor]p5:
5159 // A default constructor is trivial if:
5160 // - all the [direct subobjects] have trivial default constructors
5161 //
5162 // Note, no overload resolution is performed in this case.
5163 if (RD->hasTrivialDefaultConstructor())
5164 return true;
5165
5166 if (Selected) {
5167 // If there's a default constructor which could have been trivial, dig it
5168 // out. Otherwise, if there's any user-provided default constructor, point
5169 // to that as an example of why there's not a trivial one.
5170 CXXConstructorDecl *DefCtor = 0;
5171 if (RD->needsImplicitDefaultConstructor())
5172 S.DeclareImplicitDefaultConstructor(RD);
5173 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5174 CE = RD->ctor_end(); CI != CE; ++CI) {
5175 if (!CI->isDefaultConstructor())
5176 continue;
5177 DefCtor = *CI;
5178 if (!DefCtor->isUserProvided())
5179 break;
5180 }
5181
5182 *Selected = DefCtor;
5183 }
5184
5185 return false;
5186
5187 case Sema::CXXDestructor:
5188 // C++11 [class.dtor]p5:
5189 // A destructor is trivial if:
5190 // - all the direct [subobjects] have trivial destructors
5191 if (RD->hasTrivialDestructor())
5192 return true;
5193
5194 if (Selected) {
5195 if (RD->needsImplicitDestructor())
5196 S.DeclareImplicitDestructor(RD);
5197 *Selected = RD->getDestructor();
5198 }
5199
5200 return false;
5201
5202 case Sema::CXXCopyConstructor:
5203 // C++11 [class.copy]p12:
5204 // A copy constructor is trivial if:
5205 // - the constructor selected to copy each direct [subobject] is trivial
5206 if (RD->hasTrivialCopyConstructor()) {
5207 if (Quals == Qualifiers::Const)
5208 // We must either select the trivial copy constructor or reach an
5209 // ambiguity; no need to actually perform overload resolution.
5210 return true;
5211 } else if (!Selected) {
5212 return false;
5213 }
5214 // In C++98, we are not supposed to perform overload resolution here, but we
5215 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5216 // cases like B as having a non-trivial copy constructor:
5217 // struct A { template<typename T> A(T&); };
5218 // struct B { mutable A a; };
5219 goto NeedOverloadResolution;
5220
5221 case Sema::CXXCopyAssignment:
5222 // C++11 [class.copy]p25:
5223 // A copy assignment operator is trivial if:
5224 // - the assignment operator selected to copy each direct [subobject] is
5225 // trivial
5226 if (RD->hasTrivialCopyAssignment()) {
5227 if (Quals == Qualifiers::Const)
5228 return true;
5229 } else if (!Selected) {
5230 return false;
5231 }
5232 // In C++98, we are not supposed to perform overload resolution here, but we
5233 // treat that as a language defect.
5234 goto NeedOverloadResolution;
5235
5236 case Sema::CXXMoveConstructor:
5237 case Sema::CXXMoveAssignment:
5238 NeedOverloadResolution:
5239 Sema::SpecialMemberOverloadResult *SMOR =
5240 S.LookupSpecialMember(RD, CSM,
5241 Quals & Qualifiers::Const,
5242 Quals & Qualifiers::Volatile,
5243 /*RValueThis*/false, /*ConstThis*/false,
5244 /*VolatileThis*/false);
5245
5246 // The standard doesn't describe how to behave if the lookup is ambiguous.
5247 // We treat it as not making the member non-trivial, just like the standard
5248 // mandates for the default constructor. This should rarely matter, because
5249 // the member will also be deleted.
5250 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5251 return true;
5252
5253 if (!SMOR->getMethod()) {
5254 assert(SMOR->getKind() ==
5255 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5256 return false;
5257 }
5258
5259 // We deliberately don't check if we found a deleted special member. We're
5260 // not supposed to!
5261 if (Selected)
5262 *Selected = SMOR->getMethod();
5263 return SMOR->getMethod()->isTrivial();
5264 }
5265
5266 llvm_unreachable("unknown special method kind");
5267}
5268
Benjamin Kramera574c892013-02-15 12:30:38 +00005269static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005270 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5271 CI != CE; ++CI)
5272 if (!CI->isImplicit())
5273 return *CI;
5274
5275 // Look for constructor templates.
5276 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5277 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5278 if (CXXConstructorDecl *CD =
5279 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5280 return CD;
5281 }
5282
5283 return 0;
5284}
5285
5286/// The kind of subobject we are checking for triviality. The values of this
5287/// enumeration are used in diagnostics.
5288enum TrivialSubobjectKind {
5289 /// The subobject is a base class.
5290 TSK_BaseClass,
5291 /// The subobject is a non-static data member.
5292 TSK_Field,
5293 /// The object is actually the complete object.
5294 TSK_CompleteObject
5295};
5296
5297/// Check whether the special member selected for a given type would be trivial.
5298static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5299 QualType SubType,
5300 Sema::CXXSpecialMember CSM,
5301 TrivialSubobjectKind Kind,
5302 bool Diagnose) {
5303 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5304 if (!SubRD)
5305 return true;
5306
5307 CXXMethodDecl *Selected;
5308 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5309 Diagnose ? &Selected : 0))
5310 return true;
5311
5312 if (Diagnose) {
5313 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5314 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5315 << Kind << SubType.getUnqualifiedType();
5316 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5317 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5318 } else if (!Selected)
5319 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5320 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5321 else if (Selected->isUserProvided()) {
5322 if (Kind == TSK_CompleteObject)
5323 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5324 << Kind << SubType.getUnqualifiedType() << CSM;
5325 else {
5326 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5327 << Kind << SubType.getUnqualifiedType() << CSM;
5328 S.Diag(Selected->getLocation(), diag::note_declared_at);
5329 }
5330 } else {
5331 if (Kind != TSK_CompleteObject)
5332 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5333 << Kind << SubType.getUnqualifiedType() << CSM;
5334
5335 // Explain why the defaulted or deleted special member isn't trivial.
5336 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5337 }
5338 }
5339
5340 return false;
5341}
5342
5343/// Check whether the members of a class type allow a special member to be
5344/// trivial.
5345static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5346 Sema::CXXSpecialMember CSM,
5347 bool ConstArg, bool Diagnose) {
5348 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5349 FE = RD->field_end(); FI != FE; ++FI) {
5350 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5351 continue;
5352
5353 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5354
5355 // Pretend anonymous struct or union members are members of this class.
5356 if (FI->isAnonymousStructOrUnion()) {
5357 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5358 CSM, ConstArg, Diagnose))
5359 return false;
5360 continue;
5361 }
5362
5363 // C++11 [class.ctor]p5:
5364 // A default constructor is trivial if [...]
5365 // -- no non-static data member of its class has a
5366 // brace-or-equal-initializer
5367 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5368 if (Diagnose)
5369 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5370 return false;
5371 }
5372
5373 // Objective C ARC 4.3.5:
5374 // [...] nontrivally ownership-qualified types are [...] not trivially
5375 // default constructible, copy constructible, move constructible, copy
5376 // assignable, move assignable, or destructible [...]
5377 if (S.getLangOpts().ObjCAutoRefCount &&
5378 FieldType.hasNonTrivialObjCLifetime()) {
5379 if (Diagnose)
5380 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5381 << RD << FieldType.getObjCLifetime();
5382 return false;
5383 }
5384
5385 if (ConstArg && !FI->isMutable())
5386 FieldType.addConst();
5387 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5388 TSK_Field, Diagnose))
5389 return false;
5390 }
5391
5392 return true;
5393}
5394
5395/// Diagnose why the specified class does not have a trivial special member of
5396/// the given kind.
5397void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5398 QualType Ty = Context.getRecordType(RD);
5399 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5400 Ty.addConst();
5401
5402 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5403 TSK_CompleteObject, /*Diagnose*/true);
5404}
5405
5406/// Determine whether a defaulted or deleted special member function is trivial,
5407/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5408/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5409bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5410 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005411 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5412
5413 CXXRecordDecl *RD = MD->getParent();
5414
5415 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005416
5417 // C++11 [class.copy]p12, p25:
5418 // A [special member] is trivial if its declared parameter type is the same
5419 // as if it had been implicitly declared [...]
5420 switch (CSM) {
5421 case CXXDefaultConstructor:
5422 case CXXDestructor:
5423 // Trivial default constructors and destructors cannot have parameters.
5424 break;
5425
5426 case CXXCopyConstructor:
5427 case CXXCopyAssignment: {
5428 // Trivial copy operations always have const, non-volatile parameter types.
5429 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005430 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005431 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5432 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5433 if (Diagnose)
5434 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5435 << Param0->getSourceRange() << Param0->getType()
5436 << Context.getLValueReferenceType(
5437 Context.getRecordType(RD).withConst());
5438 return false;
5439 }
5440 break;
5441 }
5442
5443 case CXXMoveConstructor:
5444 case CXXMoveAssignment: {
5445 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005446 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005447 const RValueReferenceType *RT =
5448 Param0->getType()->getAs<RValueReferenceType>();
5449 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5450 if (Diagnose)
5451 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5452 << Param0->getSourceRange() << Param0->getType()
5453 << Context.getRValueReferenceType(Context.getRecordType(RD));
5454 return false;
5455 }
5456 break;
5457 }
5458
5459 case CXXInvalid:
5460 llvm_unreachable("not a special member");
5461 }
5462
5463 // FIXME: We require that the parameter-declaration-clause is equivalent to
5464 // that of an implicit declaration, not just that the declared parameter type
5465 // matches, in order to prevent absuridities like a function simultaneously
5466 // being a trivial copy constructor and a non-trivial default constructor.
5467 // This issue has not yet been assigned a core issue number.
5468 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5469 if (Diagnose)
5470 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5471 diag::note_nontrivial_default_arg)
5472 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5473 return false;
5474 }
5475 if (MD->isVariadic()) {
5476 if (Diagnose)
5477 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5478 return false;
5479 }
5480
5481 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5482 // A copy/move [constructor or assignment operator] is trivial if
5483 // -- the [member] selected to copy/move each direct base class subobject
5484 // is trivial
5485 //
5486 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5487 // A [default constructor or destructor] is trivial if
5488 // -- all the direct base classes have trivial [default constructors or
5489 // destructors]
5490 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5491 BE = RD->bases_end(); BI != BE; ++BI)
5492 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5493 ConstArg ? BI->getType().withConst()
5494 : BI->getType(),
5495 CSM, TSK_BaseClass, Diagnose))
5496 return false;
5497
5498 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5499 // A copy/move [constructor or assignment operator] for a class X is
5500 // trivial if
5501 // -- for each non-static data member of X that is of class type (or array
5502 // thereof), the constructor selected to copy/move that member is
5503 // trivial
5504 //
5505 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5506 // A [default constructor or destructor] is trivial if
5507 // -- for all of the non-static data members of its class that are of class
5508 // type (or array thereof), each such class has a trivial [default
5509 // constructor or destructor]
5510 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5511 return false;
5512
5513 // C++11 [class.dtor]p5:
5514 // A destructor is trivial if [...]
5515 // -- the destructor is not virtual
5516 if (CSM == CXXDestructor && MD->isVirtual()) {
5517 if (Diagnose)
5518 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5519 return false;
5520 }
5521
5522 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5523 // A [special member] for class X is trivial if [...]
5524 // -- class X has no virtual functions and no virtual base classes
5525 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5526 if (!Diagnose)
5527 return false;
5528
5529 if (RD->getNumVBases()) {
5530 // Check for virtual bases. We already know that the corresponding
5531 // member in all bases is trivial, so vbases must all be direct.
5532 CXXBaseSpecifier &BS = *RD->vbases_begin();
5533 assert(BS.isVirtual());
5534 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5535 return false;
5536 }
5537
5538 // Must have a virtual method.
5539 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5540 ME = RD->method_end(); MI != ME; ++MI) {
5541 if (MI->isVirtual()) {
5542 SourceLocation MLoc = MI->getLocStart();
5543 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5544 return false;
5545 }
5546 }
5547
5548 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5549 }
5550
5551 // Looks like it's trivial!
5552 return true;
5553}
5554
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005555/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005556namespace {
5557 struct FindHiddenVirtualMethodData {
5558 Sema *S;
5559 CXXMethodDecl *Method;
5560 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005561 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005562 };
5563}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005564
David Blaikie5f750682012-10-19 00:53:08 +00005565/// \brief Check whether any most overriden method from MD in Methods
5566static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5567 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5568 if (MD->size_overridden_methods() == 0)
5569 return Methods.count(MD->getCanonicalDecl());
5570 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5571 E = MD->end_overridden_methods();
5572 I != E; ++I)
5573 if (CheckMostOverridenMethods(*I, Methods))
5574 return true;
5575 return false;
5576}
5577
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005578/// \brief Member lookup function that determines whether a given C++
5579/// method overloads virtual methods in a base class without overriding any,
5580/// to be used with CXXRecordDecl::lookupInBases().
5581static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5582 CXXBasePath &Path,
5583 void *UserData) {
5584 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5585
5586 FindHiddenVirtualMethodData &Data
5587 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5588
5589 DeclarationName Name = Data.Method->getDeclName();
5590 assert(Name.getNameKind() == DeclarationName::Identifier);
5591
5592 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005593 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005594 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005595 !Path.Decls.empty();
5596 Path.Decls = Path.Decls.slice(1)) {
5597 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005598 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005599 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005600 foundSameNameMethod = true;
5601 // Interested only in hidden virtual methods.
5602 if (!MD->isVirtual())
5603 continue;
5604 // If the method we are checking overrides a method from its base
5605 // don't warn about the other overloaded methods.
5606 if (!Data.S->IsOverload(Data.Method, MD, false))
5607 return true;
5608 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005609 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005610 overloadedMethods.push_back(MD);
5611 }
5612 }
5613
5614 if (foundSameNameMethod)
5615 Data.OverloadedMethods.append(overloadedMethods.begin(),
5616 overloadedMethods.end());
5617 return foundSameNameMethod;
5618}
5619
David Blaikie5f750682012-10-19 00:53:08 +00005620/// \brief Add the most overriden methods from MD to Methods
5621static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5622 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5623 if (MD->size_overridden_methods() == 0)
5624 Methods.insert(MD->getCanonicalDecl());
5625 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5626 E = MD->end_overridden_methods();
5627 I != E; ++I)
5628 AddMostOverridenMethods(*I, Methods);
5629}
5630
Eli Friedmandae92712013-09-05 23:51:03 +00005631/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005632/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005633void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5634 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005635 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005636 return;
5637
5638 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5639 /*bool RecordPaths=*/false,
5640 /*bool DetectVirtual=*/false);
5641 FindHiddenVirtualMethodData Data;
5642 Data.Method = MD;
5643 Data.S = this;
5644
5645 // Keep the base methods that were overriden or introduced in the subclass
5646 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005647 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005648 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5649 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5650 NamedDecl *ND = *I;
5651 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005652 ND = shad->getTargetDecl();
5653 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5654 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005655 }
5656
Eli Friedmandae92712013-09-05 23:51:03 +00005657 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5658 OverloadedMethods = Data.OverloadedMethods;
5659}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005660
Eli Friedmandae92712013-09-05 23:51:03 +00005661void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5662 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5663 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5664 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5665 PartialDiagnostic PD = PDiag(
5666 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5667 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5668 Diag(overloadedMD->getLocation(), PD);
5669 }
5670}
5671
5672/// \brief Diagnose methods which overload virtual methods in a base class
5673/// without overriding any.
5674void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5675 if (MD->isInvalidDecl())
5676 return;
5677
5678 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5679 MD->getLocation()) == DiagnosticsEngine::Ignored)
5680 return;
5681
5682 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5683 FindHiddenVirtualMethods(MD, OverloadedMethods);
5684 if (!OverloadedMethods.empty()) {
5685 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5686 << MD << (OverloadedMethods.size() > 1);
5687
5688 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005689 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005690}
5691
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005692void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005693 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005694 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005695 SourceLocation RBrac,
5696 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005697 if (!TagDecl)
5698 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005699
Douglas Gregor42af25f2009-05-11 19:58:34 +00005700 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005701
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005702 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5703 if (l->getKind() != AttributeList::AT_Visibility)
5704 continue;
5705 l->setInvalid();
5706 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5707 l->getName();
5708 }
5709
David Blaikie77b6de02011-09-22 02:58:26 +00005710 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005711 // strict aliasing violation!
5712 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005713 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005714
Douglas Gregor23c94db2010-07-02 17:43:08 +00005715 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005716 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005717}
5718
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005719/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5720/// special functions, such as the default constructor, copy
5721/// constructor, or destructor, to the given C++ class (C++
5722/// [special]p1). This routine can only be executed just before the
5723/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005724void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005725 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005726 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005727
Richard Smithbc2a35d2012-12-08 08:32:28 +00005728 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005729 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005730
Richard Smithbc2a35d2012-12-08 08:32:28 +00005731 // If the properties or semantics of the copy constructor couldn't be
5732 // determined while the class was being declared, force a declaration
5733 // of it now.
5734 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5735 DeclareImplicitCopyConstructor(ClassDecl);
5736 }
5737
Richard Smith80ad52f2013-01-02 11:42:31 +00005738 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005739 ++ASTContext::NumImplicitMoveConstructors;
5740
Richard Smithbc2a35d2012-12-08 08:32:28 +00005741 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5742 DeclareImplicitMoveConstructor(ClassDecl);
5743 }
5744
Douglas Gregora376d102010-07-02 21:50:04 +00005745 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5746 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005747
5748 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005749 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005750 // it shows up in the right place in the vtable and that we diagnose
5751 // problems with the implicit exception specification.
5752 if (ClassDecl->isDynamicClass() ||
5753 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005754 DeclareImplicitCopyAssignment(ClassDecl);
5755 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005756
Richard Smith80ad52f2013-01-02 11:42:31 +00005757 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005758 ++ASTContext::NumImplicitMoveAssignmentOperators;
5759
5760 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005761 if (ClassDecl->isDynamicClass() ||
5762 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005763 DeclareImplicitMoveAssignment(ClassDecl);
5764 }
5765
Douglas Gregor4923aa22010-07-02 20:37:36 +00005766 if (!ClassDecl->hasUserDeclaredDestructor()) {
5767 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005768
5769 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005770 // have to declare the destructor immediately. This ensures that, e.g., it
5771 // shows up in the right place in the vtable and that we diagnose problems
5772 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005773 if (ClassDecl->isDynamicClass() ||
5774 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005775 DeclareImplicitDestructor(ClassDecl);
5776 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005777}
5778
Francois Pichet8387e2a2011-04-22 22:18:13 +00005779void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5780 if (!D)
5781 return;
5782
5783 int NumParamList = D->getNumTemplateParameterLists();
5784 for (int i = 0; i < NumParamList; i++) {
5785 TemplateParameterList* Params = D->getTemplateParameterList(i);
5786 for (TemplateParameterList::iterator Param = Params->begin(),
5787 ParamEnd = Params->end();
5788 Param != ParamEnd; ++Param) {
5789 NamedDecl *Named = cast<NamedDecl>(*Param);
5790 if (Named->getDeclName()) {
5791 S->AddDecl(Named);
5792 IdResolver.AddDecl(Named);
5793 }
5794 }
5795 }
5796}
5797
John McCalld226f652010-08-21 09:40:31 +00005798void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005799 if (!D)
5800 return;
5801
5802 TemplateParameterList *Params = 0;
5803 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5804 Params = Template->getTemplateParameters();
5805 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5806 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5807 Params = PartialSpec->getTemplateParameters();
5808 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005809 return;
5810
Douglas Gregor6569d682009-05-27 23:11:45 +00005811 for (TemplateParameterList::iterator Param = Params->begin(),
5812 ParamEnd = Params->end();
5813 Param != ParamEnd; ++Param) {
5814 NamedDecl *Named = cast<NamedDecl>(*Param);
5815 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005816 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005817 IdResolver.AddDecl(Named);
5818 }
5819 }
5820}
5821
John McCalld226f652010-08-21 09:40:31 +00005822void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005823 if (!RecordD) return;
5824 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005825 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005826 PushDeclContext(S, Record);
5827}
5828
John McCalld226f652010-08-21 09:40:31 +00005829void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005830 if (!RecordD) return;
5831 PopDeclContext();
5832}
5833
Douglas Gregor72b505b2008-12-16 21:30:33 +00005834/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5835/// parsing a top-level (non-nested) C++ class, and we are now
5836/// parsing those parts of the given Method declaration that could
5837/// not be parsed earlier (C++ [class.mem]p2), such as default
5838/// arguments. This action should enter the scope of the given
5839/// Method declaration as if we had just parsed the qualified method
5840/// name. However, it should not bring the parameters into scope;
5841/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005842void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005843}
5844
5845/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5846/// C++ method declaration. We're (re-)introducing the given
5847/// function parameter into scope for use in parsing later parts of
5848/// the method declaration. For example, we could see an
5849/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005850void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005851 if (!ParamD)
5852 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005853
John McCalld226f652010-08-21 09:40:31 +00005854 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005855
5856 // If this parameter has an unparsed default argument, clear it out
5857 // to make way for the parsed default argument.
5858 if (Param->hasUnparsedDefaultArg())
5859 Param->setDefaultArg(0);
5860
John McCalld226f652010-08-21 09:40:31 +00005861 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005862 if (Param->getDeclName())
5863 IdResolver.AddDecl(Param);
5864}
5865
5866/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5867/// processing the delayed method declaration for Method. The method
5868/// declaration is now considered finished. There may be a separate
5869/// ActOnStartOfFunctionDef action later (not necessarily
5870/// immediately!) for this method, if it was also defined inside the
5871/// class body.
John McCalld226f652010-08-21 09:40:31 +00005872void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005873 if (!MethodD)
5874 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005875
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005876 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005877
John McCalld226f652010-08-21 09:40:31 +00005878 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005879
5880 // Now that we have our default arguments, check the constructor
5881 // again. It could produce additional diagnostics or affect whether
5882 // the class has implicitly-declared destructors, among other
5883 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005884 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5885 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005886
5887 // Check the default arguments, which we may have added.
5888 if (!Method->isInvalidDecl())
5889 CheckCXXDefaultArguments(Method);
5890}
5891
Douglas Gregor42a552f2008-11-05 20:51:48 +00005892/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005893/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005894/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005895/// emit diagnostics and set the invalid bit to true. In any case, the type
5896/// will be updated to reflect a well-formed type for the constructor and
5897/// returned.
5898QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005899 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005900 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005901
5902 // C++ [class.ctor]p3:
5903 // A constructor shall not be virtual (10.3) or static (9.4). A
5904 // constructor can be invoked for a const, volatile or const
5905 // volatile object. A constructor shall not be declared const,
5906 // volatile, or const volatile (9.3.2).
5907 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005908 if (!D.isInvalidType())
5909 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5910 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5911 << SourceRange(D.getIdentifierLoc());
5912 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005913 }
John McCalld931b082010-08-26 03:08:43 +00005914 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005915 if (!D.isInvalidType())
5916 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5917 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5918 << SourceRange(D.getIdentifierLoc());
5919 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005920 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005921 }
Mike Stump1eb44332009-09-09 15:08:12 +00005922
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005923 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005924 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005925 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005926 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5927 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005928 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005929 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5930 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005931 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005932 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5933 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005934 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005935 }
Mike Stump1eb44332009-09-09 15:08:12 +00005936
Douglas Gregorc938c162011-01-26 05:01:58 +00005937 // C++0x [class.ctor]p4:
5938 // A constructor shall not be declared with a ref-qualifier.
5939 if (FTI.hasRefQualifier()) {
5940 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5941 << FTI.RefQualifierIsLValueRef
5942 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5943 D.setInvalidType();
5944 }
5945
Douglas Gregor42a552f2008-11-05 20:51:48 +00005946 // Rebuild the function type "R" without any type qualifiers (in
5947 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005948 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005949 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005950 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5951 return R;
5952
5953 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5954 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005955 EPI.RefQualifier = RQ_None;
5956
Richard Smith07b0fdc2013-03-18 21:12:30 +00005957 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005958}
5959
Douglas Gregor72b505b2008-12-16 21:30:33 +00005960/// CheckConstructor - Checks a fully-formed constructor for
5961/// well-formedness, issuing any diagnostics required. Returns true if
5962/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005963void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005964 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005965 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5966 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005967 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005968
5969 // C++ [class.copy]p3:
5970 // A declaration of a constructor for a class X is ill-formed if
5971 // its first parameter is of type (optionally cv-qualified) X and
5972 // either there are no other parameters or else all other
5973 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005974 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005975 ((Constructor->getNumParams() == 1) ||
5976 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005977 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5978 Constructor->getTemplateSpecializationKind()
5979 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005980 QualType ParamType = Constructor->getParamDecl(0)->getType();
5981 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5982 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005983 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005984 const char *ConstRef
5985 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5986 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005987 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005988 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005989
5990 // FIXME: Rather that making the constructor invalid, we should endeavor
5991 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005992 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005993 }
5994 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005995}
5996
John McCall15442822010-08-04 01:04:25 +00005997/// CheckDestructor - Checks a fully-formed destructor definition for
5998/// well-formedness, issuing any diagnostics required. Returns true
5999/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006000bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006001 CXXRecordDecl *RD = Destructor->getParent();
6002
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006003 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006004 SourceLocation Loc;
6005
6006 if (!Destructor->isImplicit())
6007 Loc = Destructor->getLocation();
6008 else
6009 Loc = RD->getLocation();
6010
6011 // If we have a virtual destructor, look up the deallocation function
6012 FunctionDecl *OperatorDelete = 0;
6013 DeclarationName Name =
6014 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006015 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006016 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006017
Eli Friedman5f2987c2012-02-02 03:46:19 +00006018 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006019
6020 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006021 }
Anders Carlsson37909802009-11-30 21:24:50 +00006022
6023 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006024}
6025
Mike Stump1eb44332009-09-09 15:08:12 +00006026static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006027FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6028 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6029 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006030 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006031}
6032
Douglas Gregor42a552f2008-11-05 20:51:48 +00006033/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6034/// the well-formednes of the destructor declarator @p D with type @p
6035/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006036/// emit diagnostics and set the declarator to invalid. Even if this happens,
6037/// will be updated to reflect a well-formed type for the destructor and
6038/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006039QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006040 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006041 // C++ [class.dtor]p1:
6042 // [...] A typedef-name that names a class is a class-name
6043 // (7.1.3); however, a typedef-name that names a class shall not
6044 // be used as the identifier in the declarator for a destructor
6045 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006046 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006047 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006048 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006049 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006050 else if (const TemplateSpecializationType *TST =
6051 DeclaratorType->getAs<TemplateSpecializationType>())
6052 if (TST->isTypeAlias())
6053 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6054 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006055
6056 // C++ [class.dtor]p2:
6057 // A destructor is used to destroy objects of its class type. A
6058 // destructor takes no parameters, and no return type can be
6059 // specified for it (not even void). The address of a destructor
6060 // shall not be taken. A destructor shall not be static. A
6061 // destructor can be invoked for a const, volatile or const
6062 // volatile object. A destructor shall not be declared const,
6063 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006064 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006065 if (!D.isInvalidType())
6066 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6067 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006068 << SourceRange(D.getIdentifierLoc())
6069 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6070
John McCalld931b082010-08-26 03:08:43 +00006071 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006072 }
Chris Lattner65401802009-04-25 08:28:21 +00006073 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006074 // Destructors don't have return types, but the parser will
6075 // happily parse something like:
6076 //
6077 // class X {
6078 // float ~X();
6079 // };
6080 //
6081 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006082 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6083 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6084 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006085 }
Mike Stump1eb44332009-09-09 15:08:12 +00006086
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006087 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006088 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006089 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006090 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6091 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006092 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006093 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6094 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006095 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006096 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6097 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006098 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006099 }
6100
Douglas Gregorc938c162011-01-26 05:01:58 +00006101 // C++0x [class.dtor]p2:
6102 // A destructor shall not be declared with a ref-qualifier.
6103 if (FTI.hasRefQualifier()) {
6104 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6105 << FTI.RefQualifierIsLValueRef
6106 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6107 D.setInvalidType();
6108 }
6109
Douglas Gregor42a552f2008-11-05 20:51:48 +00006110 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006111 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006112 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6113
6114 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006115 FTI.freeArgs();
6116 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006117 }
6118
Mike Stump1eb44332009-09-09 15:08:12 +00006119 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006120 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006121 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006122 D.setInvalidType();
6123 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006124
6125 // Rebuild the function type "R" without any type qualifiers or
6126 // parameters (in case any of the errors above fired) and with
6127 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006128 // types.
John McCalle23cf432010-12-14 08:05:40 +00006129 if (!D.isInvalidType())
6130 return R;
6131
Douglas Gregord92ec472010-07-01 05:10:53 +00006132 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006133 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6134 EPI.Variadic = false;
6135 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006136 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006137 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006138}
6139
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006140/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6141/// well-formednes of the conversion function declarator @p D with
6142/// type @p R. If there are any errors in the declarator, this routine
6143/// will emit diagnostics and return true. Otherwise, it will return
6144/// false. Either way, the type @p R will be updated to reflect a
6145/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006146void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006147 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006148 // C++ [class.conv.fct]p1:
6149 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006150 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006151 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006152 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006153 if (!D.isInvalidType())
6154 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006155 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6156 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006157 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006158 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006159 }
John McCalla3f81372010-04-13 00:04:31 +00006160
6161 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6162
Chris Lattner6e475012009-04-25 08:35:12 +00006163 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006164 // Conversion functions don't have return types, but the parser will
6165 // happily parse something like:
6166 //
6167 // class X {
6168 // float operator bool();
6169 // };
6170 //
6171 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006172 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6173 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6174 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006175 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006176 }
6177
John McCalla3f81372010-04-13 00:04:31 +00006178 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6179
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006180 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006181 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006182 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6183
6184 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006185 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006186 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006187 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006188 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006189 D.setInvalidType();
6190 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006191
John McCalla3f81372010-04-13 00:04:31 +00006192 // Diagnose "&operator bool()" and other such nonsense. This
6193 // is actually a gcc extension which we don't support.
6194 if (Proto->getResultType() != ConvType) {
6195 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6196 << Proto->getResultType();
6197 D.setInvalidType();
6198 ConvType = Proto->getResultType();
6199 }
6200
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006201 // C++ [class.conv.fct]p4:
6202 // The conversion-type-id shall not represent a function type nor
6203 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006204 if (ConvType->isArrayType()) {
6205 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6206 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006207 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006208 } else if (ConvType->isFunctionType()) {
6209 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6210 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006211 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006212 }
6213
6214 // Rebuild the function type "R" without any parameters (in case any
6215 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006216 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006217 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006218 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006219
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006220 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006221 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006222 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006223 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006224 diag::warn_cxx98_compat_explicit_conversion_functions :
6225 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006226 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006227}
6228
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006229/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6230/// the declaration of the given C++ conversion function. This routine
6231/// is responsible for recording the conversion function in the C++
6232/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006233Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006234 assert(Conversion && "Expected to receive a conversion function declaration");
6235
Douglas Gregor9d350972008-12-12 08:25:50 +00006236 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006237
6238 // Make sure we aren't redeclaring the conversion function.
6239 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006240
6241 // C++ [class.conv.fct]p1:
6242 // [...] A conversion function is never used to convert a
6243 // (possibly cv-qualified) object to the (possibly cv-qualified)
6244 // same object type (or a reference to it), to a (possibly
6245 // cv-qualified) base class of that type (or a reference to it),
6246 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006247 // FIXME: Suppress this warning if the conversion function ends up being a
6248 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006249 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006250 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006251 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006252 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006253 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6254 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006255 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006256 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006257 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6258 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006259 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006260 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006261 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006262 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006263 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006264 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006265 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006266 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006267 }
6268
Douglas Gregore80622f2010-09-29 04:25:11 +00006269 if (FunctionTemplateDecl *ConversionTemplate
6270 = Conversion->getDescribedFunctionTemplate())
6271 return ConversionTemplate;
6272
John McCalld226f652010-08-21 09:40:31 +00006273 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006274}
6275
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006276//===----------------------------------------------------------------------===//
6277// Namespace Handling
6278//===----------------------------------------------------------------------===//
6279
Richard Smithd1a55a62012-10-04 22:13:39 +00006280/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6281/// reopened.
6282static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6283 SourceLocation Loc,
6284 IdentifierInfo *II, bool *IsInline,
6285 NamespaceDecl *PrevNS) {
6286 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006287
Richard Smithc969e6a2012-10-05 01:46:25 +00006288 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6289 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6290 // inline namespaces, with the intention of bringing names into namespace std.
6291 //
6292 // We support this just well enough to get that case working; this is not
6293 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006294 if (*IsInline && II && II->getName().startswith("__atomic") &&
6295 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006296 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006297 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6298 NS = NS->getPreviousDecl())
6299 NS->setInline(*IsInline);
6300 // Patch up the lookup table for the containing namespace. This isn't really
6301 // correct, but it's good enough for this particular case.
6302 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6303 E = PrevNS->decls_end(); I != E; ++I)
6304 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6305 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6306 return;
6307 }
6308
6309 if (PrevNS->isInline())
6310 // The user probably just forgot the 'inline', so suggest that it
6311 // be added back.
6312 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6313 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6314 else
6315 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6316 << IsInline;
6317
6318 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6319 *IsInline = PrevNS->isInline();
6320}
John McCallea318642010-08-26 09:15:37 +00006321
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006322/// ActOnStartNamespaceDef - This is called at the start of a namespace
6323/// definition.
John McCalld226f652010-08-21 09:40:31 +00006324Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006325 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006326 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006327 SourceLocation IdentLoc,
6328 IdentifierInfo *II,
6329 SourceLocation LBrace,
6330 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006331 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6332 // For anonymous namespace, take the location of the left brace.
6333 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006334 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006335 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006336 bool IsStd = false;
6337 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006338 Scope *DeclRegionScope = NamespcScope->getParent();
6339
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006340 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006341 if (II) {
6342 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006343 // The identifier in an original-namespace-definition shall not
6344 // have been previously defined in the declarative region in
6345 // which the original-namespace-definition appears. The
6346 // identifier in an original-namespace-definition is the name of
6347 // the namespace. Subsequently in that declarative region, it is
6348 // treated as an original-namespace-name.
6349 //
6350 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006351 // look through using directives, just look for any ordinary names.
6352
6353 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006354 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6355 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006356 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006357 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6358 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6359 ++I) {
6360 if ((*I)->getIdentifierNamespace() & IDNS) {
6361 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006362 break;
6363 }
6364 }
6365
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006366 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6367
6368 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006369 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006370 if (IsInline != PrevNS->isInline())
6371 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6372 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006373 } else if (PrevDecl) {
6374 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006375 Diag(Loc, diag::err_redefinition_different_kind)
6376 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006377 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006378 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006379 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006380 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006381 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006382 // This is the first "real" definition of the namespace "std", so update
6383 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006384 PrevNS = getStdNamespace();
6385 IsStd = true;
6386 AddToKnown = !IsInline;
6387 } else {
6388 // We've seen this namespace for the first time.
6389 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006390 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006391 } else {
John McCall9aeed322009-10-01 00:25:31 +00006392 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006393
6394 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006395 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006396 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006397 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006398 } else {
6399 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006400 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006401 }
6402
Richard Smithd1a55a62012-10-04 22:13:39 +00006403 if (PrevNS && IsInline != PrevNS->isInline())
6404 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6405 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006406 }
6407
6408 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6409 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006410 if (IsInvalid)
6411 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006412
6413 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006414
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006415 // FIXME: Should we be merging attributes?
6416 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006417 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006418
6419 if (IsStd)
6420 StdNamespace = Namespc;
6421 if (AddToKnown)
6422 KnownNamespaces[Namespc] = false;
6423
6424 if (II) {
6425 PushOnScopeChains(Namespc, DeclRegionScope);
6426 } else {
6427 // Link the anonymous namespace into its parent.
6428 DeclContext *Parent = CurContext->getRedeclContext();
6429 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6430 TU->setAnonymousNamespace(Namespc);
6431 } else {
6432 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006433 }
John McCall9aeed322009-10-01 00:25:31 +00006434
Douglas Gregora4181472010-03-24 00:46:35 +00006435 CurContext->addDecl(Namespc);
6436
John McCall9aeed322009-10-01 00:25:31 +00006437 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6438 // behaves as if it were replaced by
6439 // namespace unique { /* empty body */ }
6440 // using namespace unique;
6441 // namespace unique { namespace-body }
6442 // where all occurrences of 'unique' in a translation unit are
6443 // replaced by the same identifier and this identifier differs
6444 // from all other identifiers in the entire program.
6445
6446 // We just create the namespace with an empty name and then add an
6447 // implicit using declaration, just like the standard suggests.
6448 //
6449 // CodeGen enforces the "universally unique" aspect by giving all
6450 // declarations semantically contained within an anonymous
6451 // namespace internal linkage.
6452
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006453 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006454 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006455 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006456 /* 'using' */ LBrace,
6457 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006458 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006459 /* identifier */ SourceLocation(),
6460 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006461 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006462 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006463 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006464 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006465 }
6466
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006467 ActOnDocumentableDecl(Namespc);
6468
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006469 // Although we could have an invalid decl (i.e. the namespace name is a
6470 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006471 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6472 // for the namespace has the declarations that showed up in that particular
6473 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006474 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006475 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006476}
6477
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006478/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6479/// is a namespace alias, returns the namespace it points to.
6480static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6481 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6482 return AD->getNamespace();
6483 return dyn_cast_or_null<NamespaceDecl>(D);
6484}
6485
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006486/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6487/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006488void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006489 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6490 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006491 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006492 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006493 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006494 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006495}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006496
John McCall384aff82010-08-25 07:42:41 +00006497CXXRecordDecl *Sema::getStdBadAlloc() const {
6498 return cast_or_null<CXXRecordDecl>(
6499 StdBadAlloc.get(Context.getExternalSource()));
6500}
6501
6502NamespaceDecl *Sema::getStdNamespace() const {
6503 return cast_or_null<NamespaceDecl>(
6504 StdNamespace.get(Context.getExternalSource()));
6505}
6506
Douglas Gregor66992202010-06-29 17:53:46 +00006507/// \brief Retrieve the special "std" namespace, which may require us to
6508/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006509NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006510 if (!StdNamespace) {
6511 // The "std" namespace has not yet been defined, so build one implicitly.
6512 StdNamespace = NamespaceDecl::Create(Context,
6513 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006514 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006515 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006516 &PP.getIdentifierTable().get("std"),
6517 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006518 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006519 }
6520
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006521 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006522}
6523
Sebastian Redl395e04d2012-01-17 22:49:33 +00006524bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006525 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006526 "Looking for std::initializer_list outside of C++.");
6527
6528 // We're looking for implicit instantiations of
6529 // template <typename E> class std::initializer_list.
6530
6531 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6532 return false;
6533
Sebastian Redl84760e32012-01-17 22:49:58 +00006534 ClassTemplateDecl *Template = 0;
6535 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006536
Sebastian Redl84760e32012-01-17 22:49:58 +00006537 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006538
Sebastian Redl84760e32012-01-17 22:49:58 +00006539 ClassTemplateSpecializationDecl *Specialization =
6540 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6541 if (!Specialization)
6542 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006543
Sebastian Redl84760e32012-01-17 22:49:58 +00006544 Template = Specialization->getSpecializedTemplate();
6545 Arguments = Specialization->getTemplateArgs().data();
6546 } else if (const TemplateSpecializationType *TST =
6547 Ty->getAs<TemplateSpecializationType>()) {
6548 Template = dyn_cast_or_null<ClassTemplateDecl>(
6549 TST->getTemplateName().getAsTemplateDecl());
6550 Arguments = TST->getArgs();
6551 }
6552 if (!Template)
6553 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006554
6555 if (!StdInitializerList) {
6556 // Haven't recognized std::initializer_list yet, maybe this is it.
6557 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6558 if (TemplateClass->getIdentifier() !=
6559 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006560 !getStdNamespace()->InEnclosingNamespaceSetOf(
6561 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006562 return false;
6563 // This is a template called std::initializer_list, but is it the right
6564 // template?
6565 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006566 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006567 return false;
6568 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6569 return false;
6570
6571 // It's the right template.
6572 StdInitializerList = Template;
6573 }
6574
6575 if (Template != StdInitializerList)
6576 return false;
6577
6578 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006579 if (Element)
6580 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006581 return true;
6582}
6583
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006584static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6585 NamespaceDecl *Std = S.getStdNamespace();
6586 if (!Std) {
6587 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6588 return 0;
6589 }
6590
6591 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6592 Loc, Sema::LookupOrdinaryName);
6593 if (!S.LookupQualifiedName(Result, Std)) {
6594 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6595 return 0;
6596 }
6597 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6598 if (!Template) {
6599 Result.suppressDiagnostics();
6600 // We found something weird. Complain about the first thing we found.
6601 NamedDecl *Found = *Result.begin();
6602 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6603 return 0;
6604 }
6605
6606 // We found some template called std::initializer_list. Now verify that it's
6607 // correct.
6608 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006609 if (Params->getMinRequiredArguments() != 1 ||
6610 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006611 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6612 return 0;
6613 }
6614
6615 return Template;
6616}
6617
6618QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6619 if (!StdInitializerList) {
6620 StdInitializerList = LookupStdInitializerList(*this, Loc);
6621 if (!StdInitializerList)
6622 return QualType();
6623 }
6624
6625 TemplateArgumentListInfo Args(Loc, Loc);
6626 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6627 Context.getTrivialTypeSourceInfo(Element,
6628 Loc)));
6629 return Context.getCanonicalType(
6630 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6631}
6632
Sebastian Redl98d36062012-01-17 22:50:14 +00006633bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6634 // C++ [dcl.init.list]p2:
6635 // A constructor is an initializer-list constructor if its first parameter
6636 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6637 // std::initializer_list<E> for some type E, and either there are no other
6638 // parameters or else all other parameters have default arguments.
6639 if (Ctor->getNumParams() < 1 ||
6640 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6641 return false;
6642
6643 QualType ArgType = Ctor->getParamDecl(0)->getType();
6644 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6645 ArgType = RT->getPointeeType().getUnqualifiedType();
6646
6647 return isStdInitializerList(ArgType, 0);
6648}
6649
Douglas Gregor9172aa62011-03-26 22:25:30 +00006650/// \brief Determine whether a using statement is in a context where it will be
6651/// apply in all contexts.
6652static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6653 switch (CurContext->getDeclKind()) {
6654 case Decl::TranslationUnit:
6655 return true;
6656 case Decl::LinkageSpec:
6657 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6658 default:
6659 return false;
6660 }
6661}
6662
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006663namespace {
6664
6665// Callback to only accept typo corrections that are namespaces.
6666class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006667public:
6668 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6669 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006670 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006671 return false;
6672 }
6673};
6674
6675}
6676
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006677static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6678 CXXScopeSpec &SS,
6679 SourceLocation IdentLoc,
6680 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006681 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006682 R.clear();
6683 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006684 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006685 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006686 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006687 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6688 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006689 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006690 S.diagnoseTypo(Corrected,
6691 S.PDiag(diag::err_using_directive_member_suggest)
6692 << Ident << DC << DroppedSpecifier << SS.getRange(),
6693 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006694 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006695 S.diagnoseTypo(Corrected,
6696 S.PDiag(diag::err_using_directive_suggest) << Ident,
6697 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006698 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006699 R.addDecl(Corrected.getCorrectionDecl());
6700 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006701 }
6702 return false;
6703}
6704
John McCalld226f652010-08-21 09:40:31 +00006705Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006706 SourceLocation UsingLoc,
6707 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006708 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006709 SourceLocation IdentLoc,
6710 IdentifierInfo *NamespcName,
6711 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006712 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6713 assert(NamespcName && "Invalid NamespcName.");
6714 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006715
6716 // This can only happen along a recovery path.
6717 while (S->getFlags() & Scope::TemplateParamScope)
6718 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006719 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006720
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006721 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006722 NestedNameSpecifier *Qualifier = 0;
6723 if (SS.isSet())
6724 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6725
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006726 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006727 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6728 LookupParsedName(R, S, &SS);
6729 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006730 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006731
Douglas Gregor66992202010-06-29 17:53:46 +00006732 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006733 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006734 // Allow "using namespace std;" or "using namespace ::std;" even if
6735 // "std" hasn't been defined yet, for GCC compatibility.
6736 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6737 NamespcName->isStr("std")) {
6738 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006739 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006740 R.resolveKind();
6741 }
6742 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006743 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006744 }
6745
John McCallf36e02d2009-10-09 21:13:30 +00006746 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006747 NamedDecl *Named = R.getFoundDecl();
6748 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6749 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006750 // C++ [namespace.udir]p1:
6751 // A using-directive specifies that the names in the nominated
6752 // namespace can be used in the scope in which the
6753 // using-directive appears after the using-directive. During
6754 // unqualified name lookup (3.4.1), the names appear as if they
6755 // were declared in the nearest enclosing namespace which
6756 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006757 // namespace. [Note: in this context, "contains" means "contains
6758 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006759
6760 // Find enclosing context containing both using-directive and
6761 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006762 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006763 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6764 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6765 CommonAncestor = CommonAncestor->getParent();
6766
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006767 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006768 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006769 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006770
Douglas Gregor9172aa62011-03-26 22:25:30 +00006771 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006772 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006773 Diag(IdentLoc, diag::warn_using_directive_in_header);
6774 }
6775
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006776 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006777 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006778 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006779 }
6780
Richard Smith6b3d3e52013-02-20 19:22:51 +00006781 if (UDir)
6782 ProcessDeclAttributeList(S, UDir, AttrList);
6783
John McCalld226f652010-08-21 09:40:31 +00006784 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006785}
6786
6787void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006788 // If the scope has an associated entity and the using directive is at
6789 // namespace or translation unit scope, add the UsingDirectiveDecl into
6790 // its lookup structure so qualified name lookup can find it.
6791 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6792 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006793 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006794 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006795 // Otherwise, it is at block sope. The using-directives will affect lookup
6796 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006797 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006798}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006799
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006800
John McCalld226f652010-08-21 09:40:31 +00006801Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006802 AccessSpecifier AS,
6803 bool HasUsingKeyword,
6804 SourceLocation UsingLoc,
6805 CXXScopeSpec &SS,
6806 UnqualifiedId &Name,
6807 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006808 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006809 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006810 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006811
Douglas Gregor12c118a2009-11-04 16:30:06 +00006812 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006813 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006814 case UnqualifiedId::IK_Identifier:
6815 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006816 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006817 case UnqualifiedId::IK_ConversionFunctionId:
6818 break;
6819
6820 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006821 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006822 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006823 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006824 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006825 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006826 diag::err_using_decl_constructor)
6827 << SS.getRange();
6828
Richard Smith80ad52f2013-01-02 11:42:31 +00006829 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006830
John McCalld226f652010-08-21 09:40:31 +00006831 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006832
6833 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006834 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006835 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006836 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006837
6838 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006839 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006840 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006841 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006842 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006843
6844 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6845 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006846 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006847 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006848
Richard Smith07b0fdc2013-03-18 21:12:30 +00006849 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006850 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006851 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006852 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6853 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006854 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006855 }
6856
Douglas Gregor56c04582010-12-16 00:46:58 +00006857 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6858 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6859 return 0;
6860
John McCall9488ea12009-11-17 05:59:44 +00006861 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006862 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006863 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006864 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006865 if (UD)
6866 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006867
John McCalld226f652010-08-21 09:40:31 +00006868 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006869}
6870
Douglas Gregor09acc982010-07-07 23:08:52 +00006871/// \brief Determine whether a using declaration considers the given
6872/// declarations as "equivalent", e.g., if they are redeclarations of
6873/// the same entity or are both typedefs of the same type.
6874static bool
6875IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6876 bool &SuppressRedeclaration) {
6877 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6878 SuppressRedeclaration = false;
6879 return true;
6880 }
6881
Richard Smith162e1c12011-04-15 14:24:37 +00006882 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6883 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006884 SuppressRedeclaration = true;
6885 return Context.hasSameType(TD1->getUnderlyingType(),
6886 TD2->getUnderlyingType());
6887 }
6888
6889 return false;
6890}
6891
6892
John McCall9f54ad42009-12-10 09:41:52 +00006893/// Determines whether to create a using shadow decl for a particular
6894/// decl, given the set of decls existing prior to this using lookup.
6895bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6896 const LookupResult &Previous) {
6897 // Diagnose finding a decl which is not from a base class of the
6898 // current class. We do this now because there are cases where this
6899 // function will silently decide not to build a shadow decl, which
6900 // will pre-empt further diagnostics.
6901 //
6902 // We don't need to do this in C++0x because we do the check once on
6903 // the qualifier.
6904 //
6905 // FIXME: diagnose the following if we care enough:
6906 // struct A { int foo; };
6907 // struct B : A { using A::foo; };
6908 // template <class T> struct C : A {};
6909 // template <class T> struct D : C<T> { using B::foo; } // <---
6910 // This is invalid (during instantiation) in C++03 because B::foo
6911 // resolves to the using decl in B, which is not a base class of D<T>.
6912 // We can't diagnose it immediately because C<T> is an unknown
6913 // specialization. The UsingShadowDecl in D<T> then points directly
6914 // to A::foo, which will look well-formed when we instantiate.
6915 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006916 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006917 DeclContext *OrigDC = Orig->getDeclContext();
6918
6919 // Handle enums and anonymous structs.
6920 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6921 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6922 while (OrigRec->isAnonymousStructOrUnion())
6923 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6924
6925 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6926 if (OrigDC == CurContext) {
6927 Diag(Using->getLocation(),
6928 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006929 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006930 Diag(Orig->getLocation(), diag::note_using_decl_target);
6931 return true;
6932 }
6933
Douglas Gregordc355712011-02-25 00:36:19 +00006934 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006935 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006936 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006937 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006938 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006939 Diag(Orig->getLocation(), diag::note_using_decl_target);
6940 return true;
6941 }
6942 }
6943
6944 if (Previous.empty()) return false;
6945
6946 NamedDecl *Target = Orig;
6947 if (isa<UsingShadowDecl>(Target))
6948 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6949
John McCalld7533ec2009-12-11 02:33:26 +00006950 // If the target happens to be one of the previous declarations, we
6951 // don't have a conflict.
6952 //
6953 // FIXME: but we might be increasing its access, in which case we
6954 // should redeclare it.
6955 NamedDecl *NonTag = 0, *Tag = 0;
6956 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6957 I != E; ++I) {
6958 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006959 bool Result;
6960 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6961 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006962
6963 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6964 }
6965
John McCall9f54ad42009-12-10 09:41:52 +00006966 if (Target->isFunctionOrFunctionTemplate()) {
6967 FunctionDecl *FD;
6968 if (isa<FunctionTemplateDecl>(Target))
6969 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6970 else
6971 FD = cast<FunctionDecl>(Target);
6972
6973 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006974 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006975 case Ovl_Overload:
6976 return false;
6977
6978 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006979 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006980 break;
6981
6982 // We found a decl with the exact signature.
6983 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006984 // If we're in a record, we want to hide the target, so we
6985 // return true (without a diagnostic) to tell the caller not to
6986 // build a shadow decl.
6987 if (CurContext->isRecord())
6988 return true;
6989
6990 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006991 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006992 break;
6993 }
6994
6995 Diag(Target->getLocation(), diag::note_using_decl_target);
6996 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6997 return true;
6998 }
6999
7000 // Target is not a function.
7001
John McCall9f54ad42009-12-10 09:41:52 +00007002 if (isa<TagDecl>(Target)) {
7003 // No conflict between a tag and a non-tag.
7004 if (!Tag) return false;
7005
John McCall41ce66f2009-12-10 19:51:03 +00007006 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007007 Diag(Target->getLocation(), diag::note_using_decl_target);
7008 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7009 return true;
7010 }
7011
7012 // No conflict between a tag and a non-tag.
7013 if (!NonTag) return false;
7014
John McCall41ce66f2009-12-10 19:51:03 +00007015 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007016 Diag(Target->getLocation(), diag::note_using_decl_target);
7017 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7018 return true;
7019}
7020
John McCall9488ea12009-11-17 05:59:44 +00007021/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007022UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007023 UsingDecl *UD,
7024 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00007025
7026 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007027 NamedDecl *Target = Orig;
7028 if (isa<UsingShadowDecl>(Target)) {
7029 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7030 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007031 }
7032
7033 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007034 = UsingShadowDecl::Create(Context, CurContext,
7035 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007036 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00007037
7038 Shadow->setAccess(UD->getAccess());
7039 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7040 Shadow->setInvalidDecl();
7041
John McCall9488ea12009-11-17 05:59:44 +00007042 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007043 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007044 else
John McCall604e7f12009-12-08 07:46:18 +00007045 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007046
John McCall604e7f12009-12-08 07:46:18 +00007047
John McCall9f54ad42009-12-10 09:41:52 +00007048 return Shadow;
7049}
John McCall604e7f12009-12-08 07:46:18 +00007050
John McCall9f54ad42009-12-10 09:41:52 +00007051/// Hides a using shadow declaration. This is required by the current
7052/// using-decl implementation when a resolvable using declaration in a
7053/// class is followed by a declaration which would hide or override
7054/// one or more of the using decl's targets; for example:
7055///
7056/// struct Base { void foo(int); };
7057/// struct Derived : Base {
7058/// using Base::foo;
7059/// void foo(int);
7060/// };
7061///
7062/// The governing language is C++03 [namespace.udecl]p12:
7063///
7064/// When a using-declaration brings names from a base class into a
7065/// derived class scope, member functions in the derived class
7066/// override and/or hide member functions with the same name and
7067/// parameter types in a base class (rather than conflicting).
7068///
7069/// There are two ways to implement this:
7070/// (1) optimistically create shadow decls when they're not hidden
7071/// by existing declarations, or
7072/// (2) don't create any shadow decls (or at least don't make them
7073/// visible) until we've fully parsed/instantiated the class.
7074/// The problem with (1) is that we might have to retroactively remove
7075/// a shadow decl, which requires several O(n) operations because the
7076/// decl structures are (very reasonably) not designed for removal.
7077/// (2) avoids this but is very fiddly and phase-dependent.
7078void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007079 if (Shadow->getDeclName().getNameKind() ==
7080 DeclarationName::CXXConversionFunctionName)
7081 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7082
John McCall9f54ad42009-12-10 09:41:52 +00007083 // Remove it from the DeclContext...
7084 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007085
John McCall9f54ad42009-12-10 09:41:52 +00007086 // ...and the scope, if applicable...
7087 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007088 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007089 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007090 }
7091
John McCall9f54ad42009-12-10 09:41:52 +00007092 // ...and the using decl.
7093 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7094
7095 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007096 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007097}
7098
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007099namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007100class UsingValidatorCCC : public CorrectionCandidateCallback {
7101public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007102 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7103 : HasTypenameKeyword(HasTypenameKeyword),
7104 IsInstantiation(IsInstantiation) {}
7105
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007106 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7107 NamedDecl *ND = Candidate.getCorrectionDecl();
7108
7109 // Keywords are not valid here.
7110 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007111 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007112
7113 // Completely unqualified names are invalid for a 'using' declaration.
7114 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7115 return false;
7116
7117 if (isa<TypeDecl>(ND))
7118 return HasTypenameKeyword || !IsInstantiation;
7119
7120 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007121 }
7122
7123private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007124 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007125 bool IsInstantiation;
7126};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007127} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007128
John McCall7ba107a2009-11-18 02:36:19 +00007129/// Builds a using declaration.
7130///
7131/// \param IsInstantiation - Whether this call arises from an
7132/// instantiation of an unresolved using declaration. We treat
7133/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007134NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7135 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007136 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007137 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007138 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007139 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007140 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007141 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007142 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007143 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007144 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007145
Anders Carlsson550b14b2009-08-28 05:49:21 +00007146 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007147
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007148 if (SS.isEmpty()) {
7149 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007150 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007151 }
Mike Stump1eb44332009-09-09 15:08:12 +00007152
John McCall9f54ad42009-12-10 09:41:52 +00007153 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007154 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007155 ForRedeclaration);
7156 Previous.setHideTags(false);
7157 if (S) {
7158 LookupName(Previous, S);
7159
7160 // It is really dumb that we have to do this.
7161 LookupResult::Filter F = Previous.makeFilter();
7162 while (F.hasNext()) {
7163 NamedDecl *D = F.next();
7164 if (!isDeclInScope(D, CurContext, S))
7165 F.erase();
7166 }
7167 F.done();
7168 } else {
7169 assert(IsInstantiation && "no scope in non-instantiation");
7170 assert(CurContext->isRecord() && "scope not record in instantiation");
7171 LookupQualifiedName(Previous, CurContext);
7172 }
7173
John McCall9f54ad42009-12-10 09:41:52 +00007174 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007175 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7176 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007177 return 0;
7178
7179 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007180 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7181 return 0;
7182
John McCallaf8e6ed2009-11-12 03:15:40 +00007183 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007184 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007185 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007186 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007187 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007188 // FIXME: not all declaration name kinds are legal here
7189 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7190 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007191 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007192 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007193 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007194 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7195 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007196 }
John McCalled976492009-12-04 22:46:56 +00007197 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007198 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007199 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007200 }
John McCalled976492009-12-04 22:46:56 +00007201 D->setAccess(AS);
7202 CurContext->addDecl(D);
7203
7204 if (!LookupContext) return D;
7205 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007206
John McCall77bb1aa2010-05-01 00:40:08 +00007207 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007208 UD->setInvalidDecl();
7209 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007210 }
7211
Richard Smithc5a89a12012-04-02 01:30:27 +00007212 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007213 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007214 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007215 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007216 return UD;
7217 }
7218
7219 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007220
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007221 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007222
John McCall604e7f12009-12-08 07:46:18 +00007223 // Unlike most lookups, we don't always want to hide tag
7224 // declarations: tag names are visible through the using declaration
7225 // even if hidden by ordinary names, *except* in a dependent context
7226 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007227 if (!IsInstantiation)
7228 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007229
John McCallb9abd8722012-04-07 03:04:20 +00007230 // For the purposes of this lookup, we have a base object type
7231 // equal to that of the current context.
7232 if (CurContext->isRecord()) {
7233 R.setBaseObjectType(
7234 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7235 }
7236
John McCalla24dc2e2009-11-17 02:14:36 +00007237 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007238
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007239 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007240 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007241 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007242 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7243 R.getLookupKind(), S, &SS, CCC)){
7244 // We reject any correction for which ND would be NULL.
7245 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007246 R.setLookupName(Corrected.getCorrection());
7247 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007248 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007249 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007250 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7251 << NameInfo.getName() << LookupContext << 0
7252 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007253 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007254 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007255 << NameInfo.getName() << LookupContext << SS.getRange();
7256 UD->setInvalidDecl();
7257 return UD;
7258 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007259 }
7260
John McCalled976492009-12-04 22:46:56 +00007261 if (R.isAmbiguous()) {
7262 UD->setInvalidDecl();
7263 return UD;
7264 }
Mike Stump1eb44332009-09-09 15:08:12 +00007265
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007266 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007267 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007268 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007269 Diag(IdentLoc, diag::err_using_typename_non_type);
7270 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7271 Diag((*I)->getUnderlyingDecl()->getLocation(),
7272 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007273 UD->setInvalidDecl();
7274 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007275 }
7276 } else {
7277 // If we asked for a non-typename and we got a type, error out,
7278 // but only if this is an instantiation of an unresolved using
7279 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007280 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007281 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7282 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007283 UD->setInvalidDecl();
7284 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007285 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007286 }
7287
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007288 // C++0x N2914 [namespace.udecl]p6:
7289 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007290 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007291 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7292 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007293 UD->setInvalidDecl();
7294 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007295 }
Mike Stump1eb44332009-09-09 15:08:12 +00007296
John McCall9f54ad42009-12-10 09:41:52 +00007297 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7298 if (!CheckUsingShadowDecl(UD, *I, Previous))
7299 BuildUsingShadowDecl(S, UD, *I);
7300 }
John McCall9488ea12009-11-17 05:59:44 +00007301
7302 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007303}
7304
Sebastian Redlf677ea32011-02-05 19:23:19 +00007305/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007306bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007307 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007308
Douglas Gregordc355712011-02-25 00:36:19 +00007309 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007310 assert(SourceType &&
7311 "Using decl naming constructor doesn't have type in scope spec.");
7312 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7313
7314 // Check whether the named type is a direct base class.
7315 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7316 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7317 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7318 BaseIt != BaseE; ++BaseIt) {
7319 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7320 if (CanonicalSourceType == BaseType)
7321 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007322 if (BaseIt->getType()->isDependentType())
7323 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007324 }
7325
7326 if (BaseIt == BaseE) {
7327 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007328 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007329 diag::err_using_decl_constructor_not_in_direct_base)
7330 << UD->getNameInfo().getSourceRange()
7331 << QualType(SourceType, 0) << TargetClass;
7332 return true;
7333 }
7334
Richard Smithc5a89a12012-04-02 01:30:27 +00007335 if (!CurContext->isDependentContext())
7336 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007337
7338 return false;
7339}
7340
John McCall9f54ad42009-12-10 09:41:52 +00007341/// Checks that the given using declaration is not an invalid
7342/// redeclaration. Note that this is checking only for the using decl
7343/// itself, not for any ill-formedness among the UsingShadowDecls.
7344bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007345 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007346 const CXXScopeSpec &SS,
7347 SourceLocation NameLoc,
7348 const LookupResult &Prev) {
7349 // C++03 [namespace.udecl]p8:
7350 // C++0x [namespace.udecl]p10:
7351 // A using-declaration is a declaration and can therefore be used
7352 // repeatedly where (and only where) multiple declarations are
7353 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007354 //
John McCall8a726212010-11-29 18:01:58 +00007355 // That's in non-member contexts.
7356 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007357 return false;
7358
7359 NestedNameSpecifier *Qual
7360 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7361
7362 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7363 NamedDecl *D = *I;
7364
7365 bool DTypename;
7366 NestedNameSpecifier *DQual;
7367 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007368 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007369 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007370 } else if (UnresolvedUsingValueDecl *UD
7371 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7372 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007373 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007374 } else if (UnresolvedUsingTypenameDecl *UD
7375 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7376 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007377 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007378 } else continue;
7379
7380 // using decls differ if one says 'typename' and the other doesn't.
7381 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007382 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007383
7384 // using decls differ if they name different scopes (but note that
7385 // template instantiation can cause this check to trigger when it
7386 // didn't before instantiation).
7387 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7388 Context.getCanonicalNestedNameSpecifier(DQual))
7389 continue;
7390
7391 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007392 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007393 return true;
7394 }
7395
7396 return false;
7397}
7398
John McCall604e7f12009-12-08 07:46:18 +00007399
John McCalled976492009-12-04 22:46:56 +00007400/// Checks that the given nested-name qualifier used in a using decl
7401/// in the current context is appropriately related to the current
7402/// scope. If an error is found, diagnoses it and returns true.
7403bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7404 const CXXScopeSpec &SS,
7405 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007406 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007407
John McCall604e7f12009-12-08 07:46:18 +00007408 if (!CurContext->isRecord()) {
7409 // C++03 [namespace.udecl]p3:
7410 // C++0x [namespace.udecl]p8:
7411 // A using-declaration for a class member shall be a member-declaration.
7412
7413 // If we weren't able to compute a valid scope, it must be a
7414 // dependent class scope.
7415 if (!NamedContext || NamedContext->isRecord()) {
7416 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7417 << SS.getRange();
7418 return true;
7419 }
7420
7421 // Otherwise, everything is known to be fine.
7422 return false;
7423 }
7424
7425 // The current scope is a record.
7426
7427 // If the named context is dependent, we can't decide much.
7428 if (!NamedContext) {
7429 // FIXME: in C++0x, we can diagnose if we can prove that the
7430 // nested-name-specifier does not refer to a base class, which is
7431 // still possible in some cases.
7432
7433 // Otherwise we have to conservatively report that things might be
7434 // okay.
7435 return false;
7436 }
7437
7438 if (!NamedContext->isRecord()) {
7439 // Ideally this would point at the last name in the specifier,
7440 // but we don't have that level of source info.
7441 Diag(SS.getRange().getBegin(),
7442 diag::err_using_decl_nested_name_specifier_is_not_class)
7443 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7444 return true;
7445 }
7446
Douglas Gregor6fb07292010-12-21 07:41:49 +00007447 if (!NamedContext->isDependentContext() &&
7448 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7449 return true;
7450
Richard Smith80ad52f2013-01-02 11:42:31 +00007451 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007452 // C++0x [namespace.udecl]p3:
7453 // In a using-declaration used as a member-declaration, the
7454 // nested-name-specifier shall name a base class of the class
7455 // being defined.
7456
7457 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7458 cast<CXXRecordDecl>(NamedContext))) {
7459 if (CurContext == NamedContext) {
7460 Diag(NameLoc,
7461 diag::err_using_decl_nested_name_specifier_is_current_class)
7462 << SS.getRange();
7463 return true;
7464 }
7465
7466 Diag(SS.getRange().getBegin(),
7467 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7468 << (NestedNameSpecifier*) SS.getScopeRep()
7469 << cast<CXXRecordDecl>(CurContext)
7470 << SS.getRange();
7471 return true;
7472 }
7473
7474 return false;
7475 }
7476
7477 // C++03 [namespace.udecl]p4:
7478 // A using-declaration used as a member-declaration shall refer
7479 // to a member of a base class of the class being defined [etc.].
7480
7481 // Salient point: SS doesn't have to name a base class as long as
7482 // lookup only finds members from base classes. Therefore we can
7483 // diagnose here only if we can prove that that can't happen,
7484 // i.e. if the class hierarchies provably don't intersect.
7485
7486 // TODO: it would be nice if "definitely valid" results were cached
7487 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7488 // need to be repeated.
7489
7490 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007491 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007492
7493 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7494 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7495 Data->Bases.insert(Base);
7496 return true;
7497 }
7498
7499 bool hasDependentBases(const CXXRecordDecl *Class) {
7500 return !Class->forallBases(collect, this);
7501 }
7502
7503 /// Returns true if the base is dependent or is one of the
7504 /// accumulated base classes.
7505 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7506 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7507 return !Data->Bases.count(Base);
7508 }
7509
7510 bool mightShareBases(const CXXRecordDecl *Class) {
7511 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7512 }
7513 };
7514
7515 UserData Data;
7516
7517 // Returns false if we find a dependent base.
7518 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7519 return false;
7520
7521 // Returns false if the class has a dependent base or if it or one
7522 // of its bases is present in the base set of the current context.
7523 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7524 return false;
7525
7526 Diag(SS.getRange().getBegin(),
7527 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7528 << (NestedNameSpecifier*) SS.getScopeRep()
7529 << cast<CXXRecordDecl>(CurContext)
7530 << SS.getRange();
7531
7532 return true;
John McCalled976492009-12-04 22:46:56 +00007533}
7534
Richard Smith162e1c12011-04-15 14:24:37 +00007535Decl *Sema::ActOnAliasDeclaration(Scope *S,
7536 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007537 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007538 SourceLocation UsingLoc,
7539 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007540 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007541 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007542 // Skip up to the relevant declaration scope.
7543 while (S->getFlags() & Scope::TemplateParamScope)
7544 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007545 assert((S->getFlags() & Scope::DeclScope) &&
7546 "got alias-declaration outside of declaration scope");
7547
7548 if (Type.isInvalid())
7549 return 0;
7550
7551 bool Invalid = false;
7552 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7553 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007554 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007555
7556 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7557 return 0;
7558
7559 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007560 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007561 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007562 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7563 TInfo->getTypeLoc().getBeginLoc());
7564 }
Richard Smith162e1c12011-04-15 14:24:37 +00007565
7566 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7567 LookupName(Previous, S);
7568
7569 // Warn about shadowing the name of a template parameter.
7570 if (Previous.isSingleResult() &&
7571 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007572 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007573 Previous.clear();
7574 }
7575
7576 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7577 "name in alias declaration must be an identifier");
7578 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7579 Name.StartLocation,
7580 Name.Identifier, TInfo);
7581
7582 NewTD->setAccess(AS);
7583
7584 if (Invalid)
7585 NewTD->setInvalidDecl();
7586
Richard Smith6b3d3e52013-02-20 19:22:51 +00007587 ProcessDeclAttributeList(S, NewTD, AttrList);
7588
Richard Smith3e4c6c42011-05-05 21:57:07 +00007589 CheckTypedefForVariablyModifiedType(S, NewTD);
7590 Invalid |= NewTD->isInvalidDecl();
7591
Richard Smith162e1c12011-04-15 14:24:37 +00007592 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007593
7594 NamedDecl *NewND;
7595 if (TemplateParamLists.size()) {
7596 TypeAliasTemplateDecl *OldDecl = 0;
7597 TemplateParameterList *OldTemplateParams = 0;
7598
7599 if (TemplateParamLists.size() != 1) {
7600 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007601 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7602 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007603 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007604 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007605
7606 // Only consider previous declarations in the same scope.
7607 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7608 /*ExplicitInstantiationOrSpecialization*/false);
7609 if (!Previous.empty()) {
7610 Redeclaration = true;
7611
7612 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7613 if (!OldDecl && !Invalid) {
7614 Diag(UsingLoc, diag::err_redefinition_different_kind)
7615 << Name.Identifier;
7616
7617 NamedDecl *OldD = Previous.getRepresentativeDecl();
7618 if (OldD->getLocation().isValid())
7619 Diag(OldD->getLocation(), diag::note_previous_definition);
7620
7621 Invalid = true;
7622 }
7623
7624 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7625 if (TemplateParameterListsAreEqual(TemplateParams,
7626 OldDecl->getTemplateParameters(),
7627 /*Complain=*/true,
7628 TPL_TemplateMatch))
7629 OldTemplateParams = OldDecl->getTemplateParameters();
7630 else
7631 Invalid = true;
7632
7633 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7634 if (!Invalid &&
7635 !Context.hasSameType(OldTD->getUnderlyingType(),
7636 NewTD->getUnderlyingType())) {
7637 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7638 // but we can't reasonably accept it.
7639 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7640 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7641 if (OldTD->getLocation().isValid())
7642 Diag(OldTD->getLocation(), diag::note_previous_definition);
7643 Invalid = true;
7644 }
7645 }
7646 }
7647
7648 // Merge any previous default template arguments into our parameters,
7649 // and check the parameter list.
7650 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7651 TPC_TypeAliasTemplate))
7652 return 0;
7653
7654 TypeAliasTemplateDecl *NewDecl =
7655 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7656 Name.Identifier, TemplateParams,
7657 NewTD);
7658
7659 NewDecl->setAccess(AS);
7660
7661 if (Invalid)
7662 NewDecl->setInvalidDecl();
7663 else if (OldDecl)
7664 NewDecl->setPreviousDeclaration(OldDecl);
7665
7666 NewND = NewDecl;
7667 } else {
7668 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7669 NewND = NewTD;
7670 }
Richard Smith162e1c12011-04-15 14:24:37 +00007671
7672 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007673 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007674
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007675 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007676 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007677}
7678
John McCalld226f652010-08-21 09:40:31 +00007679Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007680 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007681 SourceLocation AliasLoc,
7682 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007683 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007684 SourceLocation IdentLoc,
7685 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007686
Anders Carlsson81c85c42009-03-28 23:53:49 +00007687 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007688 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7689 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007690
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007691 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007692 NamedDecl *PrevDecl
7693 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7694 ForRedeclaration);
7695 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7696 PrevDecl = 0;
7697
7698 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007699 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007700 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007701 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007702 // FIXME: At some point, we'll want to create the (redundant)
7703 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007704 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007705 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007706 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007707 }
Mike Stump1eb44332009-09-09 15:08:12 +00007708
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007709 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7710 diag::err_redefinition_different_kind;
7711 Diag(AliasLoc, DiagID) << Alias;
7712 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007713 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007714 }
7715
John McCalla24dc2e2009-11-17 02:14:36 +00007716 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007717 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007718
John McCallf36e02d2009-10-09 21:13:30 +00007719 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007720 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007721 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007722 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007723 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007724 }
Mike Stump1eb44332009-09-09 15:08:12 +00007725
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007726 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007727 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007728 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007729 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007730
John McCall3dbd3d52010-02-16 06:53:13 +00007731 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007732 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007733}
7734
Sean Hunt001cad92011-05-10 00:49:42 +00007735Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007736Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7737 CXXMethodDecl *MD) {
7738 CXXRecordDecl *ClassDecl = MD->getParent();
7739
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007740 // C++ [except.spec]p14:
7741 // An implicitly declared special member function (Clause 12) shall have an
7742 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007743 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007744 if (ClassDecl->isInvalidDecl())
7745 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007746
Sebastian Redl60618fa2011-03-12 11:50:43 +00007747 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007748 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7749 BEnd = ClassDecl->bases_end();
7750 B != BEnd; ++B) {
7751 if (B->isVirtual()) // Handled below.
7752 continue;
7753
Douglas Gregor18274032010-07-03 00:47:00 +00007754 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7755 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007756 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7757 // If this is a deleted function, add it anyway. This might be conformant
7758 // with the standard. This might not. I'm not sure. It might not matter.
7759 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007760 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007761 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007762 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007763
7764 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007765 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7766 BEnd = ClassDecl->vbases_end();
7767 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007768 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7769 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007770 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7771 // If this is a deleted function, add it anyway. This might be conformant
7772 // with the standard. This might not. I'm not sure. It might not matter.
7773 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007774 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007775 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007776 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007777
7778 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007779 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7780 FEnd = ClassDecl->field_end();
7781 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007782 if (F->hasInClassInitializer()) {
7783 if (Expr *E = F->getInClassInitializer())
7784 ExceptSpec.CalledExpr(E);
7785 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007786 // DR1351:
7787 // If the brace-or-equal-initializer of a non-static data member
7788 // invokes a defaulted default constructor of its class or of an
7789 // enclosing class in a potentially evaluated subexpression, the
7790 // program is ill-formed.
7791 //
7792 // This resolution is unworkable: the exception specification of the
7793 // default constructor can be needed in an unevaluated context, in
7794 // particular, in the operand of a noexcept-expression, and we can be
7795 // unable to compute an exception specification for an enclosed class.
7796 //
7797 // We do not allow an in-class initializer to require the evaluation
7798 // of the exception specification for any in-class initializer whose
7799 // definition is not lexically complete.
7800 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007801 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007802 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007803 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7804 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7805 // If this is a deleted function, add it anyway. This might be conformant
7806 // with the standard. This might not. I'm not sure. It might not matter.
7807 // In particular, the problem is that this function never gets called. It
7808 // might just be ill-formed because this function attempts to refer to
7809 // a deleted function here.
7810 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007811 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007812 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007813 }
John McCalle23cf432010-12-14 08:05:40 +00007814
Sean Hunt001cad92011-05-10 00:49:42 +00007815 return ExceptSpec;
7816}
7817
Richard Smith07b0fdc2013-03-18 21:12:30 +00007818Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007819Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7820 CXXRecordDecl *ClassDecl = CD->getParent();
7821
7822 // C++ [except.spec]p14:
7823 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007824 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007825 if (ClassDecl->isInvalidDecl())
7826 return ExceptSpec;
7827
7828 // Inherited constructor.
7829 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7830 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7831 // FIXME: Copying or moving the parameters could add extra exceptions to the
7832 // set, as could the default arguments for the inherited constructor. This
7833 // will be addressed when we implement the resolution of core issue 1351.
7834 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7835
7836 // Direct base-class constructors.
7837 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7838 BEnd = ClassDecl->bases_end();
7839 B != BEnd; ++B) {
7840 if (B->isVirtual()) // Handled below.
7841 continue;
7842
7843 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7844 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7845 if (BaseClassDecl == InheritedDecl)
7846 continue;
7847 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7848 if (Constructor)
7849 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7850 }
7851 }
7852
7853 // Virtual base-class constructors.
7854 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7855 BEnd = ClassDecl->vbases_end();
7856 B != BEnd; ++B) {
7857 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7858 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7859 if (BaseClassDecl == InheritedDecl)
7860 continue;
7861 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7862 if (Constructor)
7863 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7864 }
7865 }
7866
7867 // Field constructors.
7868 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7869 FEnd = ClassDecl->field_end();
7870 F != FEnd; ++F) {
7871 if (F->hasInClassInitializer()) {
7872 if (Expr *E = F->getInClassInitializer())
7873 ExceptSpec.CalledExpr(E);
7874 else if (!F->isInvalidDecl())
7875 Diag(CD->getLocation(),
7876 diag::err_in_class_initializer_references_def_ctor) << CD;
7877 } else if (const RecordType *RecordTy
7878 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7879 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7880 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7881 if (Constructor)
7882 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7883 }
7884 }
7885
Richard Smith07b0fdc2013-03-18 21:12:30 +00007886 return ExceptSpec;
7887}
7888
Richard Smithafb49182012-11-29 01:34:07 +00007889namespace {
7890/// RAII object to register a special member as being currently declared.
7891struct DeclaringSpecialMember {
7892 Sema &S;
7893 Sema::SpecialMemberDecl D;
7894 bool WasAlreadyBeingDeclared;
7895
7896 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7897 : S(S), D(RD, CSM) {
7898 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7899 if (WasAlreadyBeingDeclared)
7900 // This almost never happens, but if it does, ensure that our cache
7901 // doesn't contain a stale result.
7902 S.SpecialMemberCache.clear();
7903
7904 // FIXME: Register a note to be produced if we encounter an error while
7905 // declaring the special member.
7906 }
7907 ~DeclaringSpecialMember() {
7908 if (!WasAlreadyBeingDeclared)
7909 S.SpecialMembersBeingDeclared.erase(D);
7910 }
7911
7912 /// \brief Are we already trying to declare this special member?
7913 bool isAlreadyBeingDeclared() const {
7914 return WasAlreadyBeingDeclared;
7915 }
7916};
7917}
7918
Sean Hunt001cad92011-05-10 00:49:42 +00007919CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7920 CXXRecordDecl *ClassDecl) {
7921 // C++ [class.ctor]p5:
7922 // A default constructor for a class X is a constructor of class X
7923 // that can be called without an argument. If there is no
7924 // user-declared constructor for class X, a default constructor is
7925 // implicitly declared. An implicitly-declared default constructor
7926 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007927 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007928 "Should not build implicit default constructor!");
7929
Richard Smithafb49182012-11-29 01:34:07 +00007930 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7931 if (DSM.isAlreadyBeingDeclared())
7932 return 0;
7933
Richard Smith7756afa2012-06-10 05:43:50 +00007934 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7935 CXXDefaultConstructor,
7936 false);
7937
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007938 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007939 CanQualType ClassType
7940 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007941 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007942 DeclarationName Name
7943 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007944 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007945 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007946 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007947 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007948 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007949 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007950 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007951 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007952
7953 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00007954 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00007955 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007956
Richard Smithbc2a35d2012-12-08 08:32:28 +00007957 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7958 // constructors is easy to compute.
7959 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7960
7961 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007962 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007963
Douglas Gregor18274032010-07-03 00:47:00 +00007964 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007965 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007966
Douglas Gregor23c94db2010-07-02 17:43:08 +00007967 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007968 PushOnScopeChains(DefaultCon, S, false);
7969 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007970
Douglas Gregor32df23e2010-07-01 22:02:46 +00007971 return DefaultCon;
7972}
7973
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007974void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7975 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007976 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007977 !Constructor->doesThisDeclarationHaveABody() &&
7978 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007979 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007980
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007981 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007982 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007983
Eli Friedman9a14db32012-10-18 20:14:08 +00007984 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007985 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007986 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007987 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007988 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007989 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007990 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007991 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007992 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007993
7994 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007995 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007996
Eli Friedman86164e82013-09-05 00:02:25 +00007997 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007998 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007999
8000 if (ASTMutationListener *L = getASTMutationListener()) {
8001 L->CompletedImplicitDefinition(Constructor);
8002 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008003}
8004
Richard Smith7a614d82011-06-11 17:19:42 +00008005void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00008006 // Check that any explicitly-defaulted methods have exception specifications
8007 // compatible with their implicit exception specifications.
8008 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008009}
8010
Richard Smith4841ca52013-04-10 05:48:59 +00008011namespace {
8012/// Information on inheriting constructors to declare.
8013class InheritingConstructorInfo {
8014public:
8015 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8016 : SemaRef(SemaRef), Derived(Derived) {
8017 // Mark the constructors that we already have in the derived class.
8018 //
8019 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8020 // unless there is a user-declared constructor with the same signature in
8021 // the class where the using-declaration appears.
8022 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8023 }
8024
8025 void inheritAll(CXXRecordDecl *RD) {
8026 visitAll(RD, &InheritingConstructorInfo::inherit);
8027 }
8028
8029private:
8030 /// Information about an inheriting constructor.
8031 struct InheritingConstructor {
8032 InheritingConstructor()
8033 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8034
8035 /// If \c true, a constructor with this signature is already declared
8036 /// in the derived class.
8037 bool DeclaredInDerived;
8038
8039 /// The constructor which is inherited.
8040 const CXXConstructorDecl *BaseCtor;
8041
8042 /// The derived constructor we declared.
8043 CXXConstructorDecl *DerivedCtor;
8044 };
8045
8046 /// Inheriting constructors with a given canonical type. There can be at
8047 /// most one such non-template constructor, and any number of templated
8048 /// constructors.
8049 struct InheritingConstructorsForType {
8050 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008051 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8052 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008053
8054 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8055 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8056 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8057 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8058 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8059 false, S.TPL_TemplateMatch))
8060 return Templates[I].second;
8061 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8062 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008063 }
Richard Smith4841ca52013-04-10 05:48:59 +00008064
8065 return NonTemplate;
8066 }
8067 };
8068
8069 /// Get or create the inheriting constructor record for a constructor.
8070 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8071 QualType CtorType) {
8072 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8073 .getEntry(SemaRef, Ctor);
8074 }
8075
8076 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8077
8078 /// Process all constructors for a class.
8079 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8080 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8081 CtorE = RD->ctor_end();
8082 CtorIt != CtorE; ++CtorIt)
8083 (this->*Callback)(*CtorIt);
8084 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8085 I(RD->decls_begin()), E(RD->decls_end());
8086 I != E; ++I) {
8087 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8088 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8089 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008090 }
8091 }
Richard Smith4841ca52013-04-10 05:48:59 +00008092
8093 /// Note that a constructor (or constructor template) was declared in Derived.
8094 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8095 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8096 }
8097
8098 /// Inherit a single constructor.
8099 void inherit(const CXXConstructorDecl *Ctor) {
8100 const FunctionProtoType *CtorType =
8101 Ctor->getType()->castAs<FunctionProtoType>();
8102 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8103 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8104
8105 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8106
8107 // Core issue (no number yet): the ellipsis is always discarded.
8108 if (EPI.Variadic) {
8109 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8110 SemaRef.Diag(Ctor->getLocation(),
8111 diag::note_using_decl_constructor_ellipsis);
8112 EPI.Variadic = false;
8113 }
8114
8115 // Declare a constructor for each number of parameters.
8116 //
8117 // C++11 [class.inhctor]p1:
8118 // The candidate set of inherited constructors from the class X named in
8119 // the using-declaration consists of [... modulo defects ...] for each
8120 // constructor or constructor template of X, the set of constructors or
8121 // constructor templates that results from omitting any ellipsis parameter
8122 // specification and successively omitting parameters with a default
8123 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008124 unsigned MinParams = minParamsToInherit(Ctor);
8125 unsigned Params = Ctor->getNumParams();
8126 if (Params >= MinParams) {
8127 do
8128 declareCtor(UsingLoc, Ctor,
8129 SemaRef.Context.getFunctionType(
8130 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8131 while (Params > MinParams &&
8132 Ctor->getParamDecl(--Params)->hasDefaultArg());
8133 }
Richard Smith4841ca52013-04-10 05:48:59 +00008134 }
8135
8136 /// Find the using-declaration which specified that we should inherit the
8137 /// constructors of \p Base.
8138 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8139 // No fancy lookup required; just look for the base constructor name
8140 // directly within the derived class.
8141 ASTContext &Context = SemaRef.Context;
8142 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8143 Context.getCanonicalType(Context.getRecordType(Base)));
8144 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8145 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8146 }
8147
8148 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8149 // C++11 [class.inhctor]p3:
8150 // [F]or each constructor template in the candidate set of inherited
8151 // constructors, a constructor template is implicitly declared
8152 if (Ctor->getDescribedFunctionTemplate())
8153 return 0;
8154
8155 // For each non-template constructor in the candidate set of inherited
8156 // constructors other than a constructor having no parameters or a
8157 // copy/move constructor having a single parameter, a constructor is
8158 // implicitly declared [...]
8159 if (Ctor->getNumParams() == 0)
8160 return 1;
8161 if (Ctor->isCopyOrMoveConstructor())
8162 return 2;
8163
8164 // Per discussion on core reflector, never inherit a constructor which
8165 // would become a default, copy, or move constructor of Derived either.
8166 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8167 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8168 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8169 }
8170
8171 /// Declare a single inheriting constructor, inheriting the specified
8172 /// constructor, with the given type.
8173 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8174 QualType DerivedType) {
8175 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8176
8177 // C++11 [class.inhctor]p3:
8178 // ... a constructor is implicitly declared with the same constructor
8179 // characteristics unless there is a user-declared constructor with
8180 // the same signature in the class where the using-declaration appears
8181 if (Entry.DeclaredInDerived)
8182 return;
8183
8184 // C++11 [class.inhctor]p7:
8185 // If two using-declarations declare inheriting constructors with the
8186 // same signature, the program is ill-formed
8187 if (Entry.DerivedCtor) {
8188 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8189 // Only diagnose this once per constructor.
8190 if (Entry.DerivedCtor->isInvalidDecl())
8191 return;
8192 Entry.DerivedCtor->setInvalidDecl();
8193
8194 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8195 SemaRef.Diag(BaseCtor->getLocation(),
8196 diag::note_using_decl_constructor_conflict_current_ctor);
8197 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8198 diag::note_using_decl_constructor_conflict_previous_ctor);
8199 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8200 diag::note_using_decl_constructor_conflict_previous_using);
8201 } else {
8202 // Core issue (no number): if the same inheriting constructor is
8203 // produced by multiple base class constructors from the same base
8204 // class, the inheriting constructor is defined as deleted.
8205 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8206 }
8207
8208 return;
8209 }
8210
8211 ASTContext &Context = SemaRef.Context;
8212 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8213 Context.getCanonicalType(Context.getRecordType(Derived)));
8214 DeclarationNameInfo NameInfo(Name, UsingLoc);
8215
8216 TemplateParameterList *TemplateParams = 0;
8217 if (const FunctionTemplateDecl *FTD =
8218 BaseCtor->getDescribedFunctionTemplate()) {
8219 TemplateParams = FTD->getTemplateParameters();
8220 // We're reusing template parameters from a different DeclContext. This
8221 // is questionable at best, but works out because the template depth in
8222 // both places is guaranteed to be 0.
8223 // FIXME: Rebuild the template parameters in the new context, and
8224 // transform the function type to refer to them.
8225 }
8226
8227 // Build type source info pointing at the using-declaration. This is
8228 // required by template instantiation.
8229 TypeSourceInfo *TInfo =
8230 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8231 FunctionProtoTypeLoc ProtoLoc =
8232 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8233
8234 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8235 Context, Derived, UsingLoc, NameInfo, DerivedType,
8236 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8237 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8238
8239 // Build an unevaluated exception specification for this constructor.
8240 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8241 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8242 EPI.ExceptionSpecType = EST_Unevaluated;
8243 EPI.ExceptionSpecDecl = DerivedCtor;
8244 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8245 FPT->getArgTypes(), EPI));
8246
8247 // Build the parameter declarations.
8248 SmallVector<ParmVarDecl *, 16> ParamDecls;
8249 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8250 TypeSourceInfo *TInfo =
8251 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8252 ParmVarDecl *PD = ParmVarDecl::Create(
8253 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8254 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8255 PD->setScopeInfo(0, I);
8256 PD->setImplicit();
8257 ParamDecls.push_back(PD);
8258 ProtoLoc.setArg(I, PD);
8259 }
8260
8261 // Set up the new constructor.
8262 DerivedCtor->setAccess(BaseCtor->getAccess());
8263 DerivedCtor->setParams(ParamDecls);
8264 DerivedCtor->setInheritedConstructor(BaseCtor);
8265 if (BaseCtor->isDeleted())
8266 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8267
8268 // If this is a constructor template, build the template declaration.
8269 if (TemplateParams) {
8270 FunctionTemplateDecl *DerivedTemplate =
8271 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8272 TemplateParams, DerivedCtor);
8273 DerivedTemplate->setAccess(BaseCtor->getAccess());
8274 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8275 Derived->addDecl(DerivedTemplate);
8276 } else {
8277 Derived->addDecl(DerivedCtor);
8278 }
8279
8280 Entry.BaseCtor = BaseCtor;
8281 Entry.DerivedCtor = DerivedCtor;
8282 }
8283
8284 Sema &SemaRef;
8285 CXXRecordDecl *Derived;
8286 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8287 MapType Map;
8288};
8289}
8290
8291void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8292 // Defer declaring the inheriting constructors until the class is
8293 // instantiated.
8294 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008295 return;
8296
Richard Smith4841ca52013-04-10 05:48:59 +00008297 // Find base classes from which we might inherit constructors.
8298 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8299 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8300 BaseE = ClassDecl->bases_end();
8301 BaseIt != BaseE; ++BaseIt)
8302 if (BaseIt->getInheritConstructors())
8303 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008304
Richard Smith4841ca52013-04-10 05:48:59 +00008305 // Go no further if we're not inheriting any constructors.
8306 if (InheritedBases.empty())
8307 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008308
Richard Smith4841ca52013-04-10 05:48:59 +00008309 // Declare the inherited constructors.
8310 InheritingConstructorInfo ICI(*this, ClassDecl);
8311 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8312 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008313}
8314
Richard Smith07b0fdc2013-03-18 21:12:30 +00008315void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8316 CXXConstructorDecl *Constructor) {
8317 CXXRecordDecl *ClassDecl = Constructor->getParent();
8318 assert(Constructor->getInheritedConstructor() &&
8319 !Constructor->doesThisDeclarationHaveABody() &&
8320 !Constructor->isDeleted());
8321
8322 SynthesizedFunctionScope Scope(*this, Constructor);
8323 DiagnosticErrorTrap Trap(Diags);
8324 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8325 Trap.hasErrorOccurred()) {
8326 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8327 << Context.getTagDeclType(ClassDecl);
8328 Constructor->setInvalidDecl();
8329 return;
8330 }
8331
8332 SourceLocation Loc = Constructor->getLocation();
8333 Constructor->setBody(new (Context) CompoundStmt(Loc));
8334
Eli Friedman86164e82013-09-05 00:02:25 +00008335 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008336 MarkVTableUsed(CurrentLocation, ClassDecl);
8337
8338 if (ASTMutationListener *L = getASTMutationListener()) {
8339 L->CompletedImplicitDefinition(Constructor);
8340 }
8341}
8342
8343
Sean Huntcb45a0f2011-05-12 22:46:25 +00008344Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008345Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8346 CXXRecordDecl *ClassDecl = MD->getParent();
8347
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008348 // C++ [except.spec]p14:
8349 // An implicitly declared special member function (Clause 12) shall have
8350 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008351 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008352 if (ClassDecl->isInvalidDecl())
8353 return ExceptSpec;
8354
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008355 // Direct base-class destructors.
8356 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8357 BEnd = ClassDecl->bases_end();
8358 B != BEnd; ++B) {
8359 if (B->isVirtual()) // Handled below.
8360 continue;
8361
8362 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008363 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008364 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008365 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008366
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008367 // Virtual base-class destructors.
8368 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8369 BEnd = ClassDecl->vbases_end();
8370 B != BEnd; ++B) {
8371 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008372 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008373 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008374 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008375
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008376 // Field destructors.
8377 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8378 FEnd = ClassDecl->field_end();
8379 F != FEnd; ++F) {
8380 if (const RecordType *RecordTy
8381 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008382 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008383 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008384 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008385
Sean Huntcb45a0f2011-05-12 22:46:25 +00008386 return ExceptSpec;
8387}
8388
8389CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8390 // C++ [class.dtor]p2:
8391 // If a class has no user-declared destructor, a destructor is
8392 // declared implicitly. An implicitly-declared destructor is an
8393 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008394 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008395
Richard Smithafb49182012-11-29 01:34:07 +00008396 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8397 if (DSM.isAlreadyBeingDeclared())
8398 return 0;
8399
Douglas Gregor4923aa22010-07-02 20:37:36 +00008400 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008401 CanQualType ClassType
8402 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008403 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008404 DeclarationName Name
8405 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008406 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008407 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008408 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8409 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008410 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008411 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008412 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008413 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008414
8415 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008416 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008417 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008418
Richard Smithbc2a35d2012-12-08 08:32:28 +00008419 AddOverriddenMethods(ClassDecl, Destructor);
8420
8421 // We don't need to use SpecialMemberIsTrivial here; triviality for
8422 // destructors is easy to compute.
8423 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8424
8425 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008426 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008427
Douglas Gregor4923aa22010-07-02 20:37:36 +00008428 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008429 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008430
Douglas Gregor4923aa22010-07-02 20:37:36 +00008431 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008432 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008433 PushOnScopeChains(Destructor, S, false);
8434 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008435
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008436 return Destructor;
8437}
8438
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008439void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008440 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008441 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008442 !Destructor->doesThisDeclarationHaveABody() &&
8443 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008444 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008445 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008446 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008447
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008448 if (Destructor->isInvalidDecl())
8449 return;
8450
Eli Friedman9a14db32012-10-18 20:14:08 +00008451 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008452
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008453 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008454 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8455 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008456
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008457 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008458 Diag(CurrentLocation, diag::note_member_synthesized_at)
8459 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8460
8461 Destructor->setInvalidDecl();
8462 return;
8463 }
8464
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008465 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008466 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008467 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008468 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008469
8470 if (ASTMutationListener *L = getASTMutationListener()) {
8471 L->CompletedImplicitDefinition(Destructor);
8472 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008473}
8474
Richard Smitha4156b82012-04-21 18:42:51 +00008475/// \brief Perform any semantic analysis which needs to be delayed until all
8476/// pending class member declarations have been parsed.
8477void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008478 // If the context is an invalid C++ class, just suppress these checks.
8479 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8480 if (Record->isInvalidDecl()) {
8481 DelayedDestructorExceptionSpecChecks.clear();
8482 return;
8483 }
8484 }
8485
Richard Smitha4156b82012-04-21 18:42:51 +00008486 // Perform any deferred checking of exception specifications for virtual
8487 // destructors.
8488 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8489 i != e; ++i) {
8490 const CXXDestructorDecl *Dtor =
8491 DelayedDestructorExceptionSpecChecks[i].first;
8492 assert(!Dtor->getParent()->isDependentType() &&
8493 "Should not ever add destructors of templates into the list.");
8494 CheckOverridingFunctionExceptionSpec(Dtor,
8495 DelayedDestructorExceptionSpecChecks[i].second);
8496 }
8497 DelayedDestructorExceptionSpecChecks.clear();
8498}
8499
Richard Smithb9d0b762012-07-27 04:22:15 +00008500void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8501 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008502 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008503 "adjusting dtor exception specs was introduced in c++11");
8504
Sebastian Redl0ee33912011-05-19 05:13:44 +00008505 // C++11 [class.dtor]p3:
8506 // A declaration of a destructor that does not have an exception-
8507 // specification is implicitly considered to have the same exception-
8508 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008509 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008510 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008511 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008512 return;
8513
Chandler Carruth3f224b22011-09-20 04:55:26 +00008514 // Replace the destructor's type, building off the existing one. Fortunately,
8515 // the only thing of interest in the destructor type is its extended info.
8516 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008517 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8518 EPI.ExceptionSpecType = EST_Unevaluated;
8519 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008520 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008521
Sebastian Redl0ee33912011-05-19 05:13:44 +00008522 // FIXME: If the destructor has a body that could throw, and the newly created
8523 // spec doesn't allow exceptions, we should emit a warning, because this
8524 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008525 // However, we don't have a body or an exception specification yet, so it
8526 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008527}
8528
Pavel Labath66ea35d2013-08-30 08:52:28 +00008529namespace {
8530/// \brief An abstract base class for all helper classes used in building the
8531// copy/move operators. These classes serve as factory functions and help us
8532// avoid using the same Expr* in the AST twice.
8533class ExprBuilder {
8534 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8535 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8536
8537protected:
8538 static Expr *assertNotNull(Expr *E) {
8539 assert(E && "Expression construction must not fail.");
8540 return E;
8541 }
8542
8543public:
8544 ExprBuilder() {}
8545 virtual ~ExprBuilder() {}
8546
8547 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8548};
8549
8550class RefBuilder: public ExprBuilder {
8551 VarDecl *Var;
8552 QualType VarType;
8553
8554public:
8555 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8556 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8557 }
8558
8559 RefBuilder(VarDecl *Var, QualType VarType)
8560 : Var(Var), VarType(VarType) {}
8561};
8562
8563class ThisBuilder: public ExprBuilder {
8564public:
8565 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8566 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8567 }
8568};
8569
8570class CastBuilder: public ExprBuilder {
8571 const ExprBuilder &Builder;
8572 QualType Type;
8573 ExprValueKind Kind;
8574 const CXXCastPath &Path;
8575
8576public:
8577 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8578 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8579 CK_UncheckedDerivedToBase, Kind,
8580 &Path).take());
8581 }
8582
8583 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8584 const CXXCastPath &Path)
8585 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8586};
8587
8588class DerefBuilder: public ExprBuilder {
8589 const ExprBuilder &Builder;
8590
8591public:
8592 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8593 return assertNotNull(
8594 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8595 }
8596
8597 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8598};
8599
8600class MemberBuilder: public ExprBuilder {
8601 const ExprBuilder &Builder;
8602 QualType Type;
8603 CXXScopeSpec SS;
8604 bool IsArrow;
8605 LookupResult &MemberLookup;
8606
8607public:
8608 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8609 return assertNotNull(S.BuildMemberReferenceExpr(
8610 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8611 MemberLookup, 0).take());
8612 }
8613
8614 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8615 LookupResult &MemberLookup)
8616 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8617 MemberLookup(MemberLookup) {}
8618};
8619
8620class MoveCastBuilder: public ExprBuilder {
8621 const ExprBuilder &Builder;
8622
8623public:
8624 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8625 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8626 }
8627
8628 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8629};
8630
8631class LvalueConvBuilder: public ExprBuilder {
8632 const ExprBuilder &Builder;
8633
8634public:
8635 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8636 return assertNotNull(
8637 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8638 }
8639
8640 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8641};
8642
8643class SubscriptBuilder: public ExprBuilder {
8644 const ExprBuilder &Base;
8645 const ExprBuilder &Index;
8646
8647public:
8648 virtual Expr *build(Sema &S, SourceLocation Loc) const
8649 LLVM_OVERRIDE {
8650 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8651 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8652 }
8653
8654 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8655 : Base(Base), Index(Index) {}
8656};
8657
8658} // end anonymous namespace
8659
Richard Smith8c889532012-11-14 00:50:40 +00008660/// When generating a defaulted copy or move assignment operator, if a field
8661/// should be copied with __builtin_memcpy rather than via explicit assignments,
8662/// do so. This optimization only applies for arrays of scalars, and for arrays
8663/// of class type where the selected copy/move-assignment operator is trivial.
8664static StmtResult
8665buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008666 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008667 // Compute the size of the memory buffer to be copied.
8668 QualType SizeType = S.Context.getSizeType();
8669 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8670 S.Context.getTypeSizeInChars(T).getQuantity());
8671
8672 // Take the address of the field references for "from" and "to". We
8673 // directly construct UnaryOperators here because semantic analysis
8674 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008675 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008676 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8677 S.Context.getPointerType(From->getType()),
8678 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008679 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008680 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8681 S.Context.getPointerType(To->getType()),
8682 VK_RValue, OK_Ordinary, Loc);
8683
8684 const Type *E = T->getBaseElementTypeUnsafe();
8685 bool NeedsCollectableMemCpy =
8686 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8687
8688 // Create a reference to the __builtin_objc_memmove_collectable function
8689 StringRef MemCpyName = NeedsCollectableMemCpy ?
8690 "__builtin_objc_memmove_collectable" :
8691 "__builtin_memcpy";
8692 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8693 Sema::LookupOrdinaryName);
8694 S.LookupName(R, S.TUScope, true);
8695
8696 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8697 if (!MemCpy)
8698 // Something went horribly wrong earlier, and we will have complained
8699 // about it.
8700 return StmtError();
8701
8702 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8703 VK_RValue, Loc, 0);
8704 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8705
8706 Expr *CallArgs[] = {
8707 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8708 };
8709 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8710 Loc, CallArgs, Loc);
8711
8712 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8713 return S.Owned(Call.takeAs<Stmt>());
8714}
8715
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008716/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008717/// \c To.
8718///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008719/// This routine is used to copy/move the members of a class with an
8720/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008721/// copied are arrays, this routine builds for loops to copy them.
8722///
8723/// \param S The Sema object used for type-checking.
8724///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008725/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008726///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008727/// \param T The type of the expressions being copied/moved. Both expressions
8728/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008729///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008730/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008731///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008732/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008733///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008734/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008735/// Otherwise, it's a non-static member subobject.
8736///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008737/// \param Copying Whether we're copying or moving.
8738///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008739/// \param Depth Internal parameter recording the depth of the recursion.
8740///
Richard Smith8c889532012-11-14 00:50:40 +00008741/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8742/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008743static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008744buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008745 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008746 bool CopyingBaseSubobject, bool Copying,
8747 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008748 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008749 // Each subobject is assigned in the manner appropriate to its type:
8750 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008751 // - if the subobject is of class type, as if by a call to operator= with
8752 // the subobject as the object expression and the corresponding
8753 // subobject of x as a single function argument (as if by explicit
8754 // qualification; that is, ignoring any possible virtual overriding
8755 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008756 //
8757 // C++03 [class.copy]p13:
8758 // - if the subobject is of class type, the copy assignment operator for
8759 // the class is used (as if by explicit qualification; that is,
8760 // ignoring any possible virtual overriding functions in more derived
8761 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008762 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8763 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008764
Douglas Gregor06a9f362010-05-01 20:49:11 +00008765 // Look for operator=.
8766 DeclarationName Name
8767 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8768 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8769 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008770
Richard Smith044c8aa2012-11-13 00:54:12 +00008771 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8772 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008773 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008774 LookupResult::Filter F = OpLookup.makeFilter();
8775 while (F.hasNext()) {
8776 NamedDecl *D = F.next();
8777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8778 if (Method->isCopyAssignmentOperator() ||
8779 (!Copying && Method->isMoveAssignmentOperator()))
8780 continue;
8781
8782 F.erase();
8783 }
8784 F.done();
John McCallb0207482010-03-16 06:11:48 +00008785 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008786
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008787 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008788 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008789 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008790 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008791 // ambiguities), we need to cast "this" to that subobject type; to
8792 // ensure that we don't go through the virtual call mechanism, we need
8793 // to qualify the operator= name with the base class (see below). However,
8794 // this means that if the base class has a protected copy assignment
8795 // operator, the protected member access check will fail. So, we
8796 // rewrite "protected" access to "public" access in this case, since we
8797 // know by construction that we're calling from a derived class.
8798 if (CopyingBaseSubobject) {
8799 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8800 L != LEnd; ++L) {
8801 if (L.getAccess() == AS_protected)
8802 L.setAccess(AS_public);
8803 }
8804 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008805
Douglas Gregor06a9f362010-05-01 20:49:11 +00008806 // Create the nested-name-specifier that will be used to qualify the
8807 // reference to operator=; this is required to suppress the virtual
8808 // call mechanism.
8809 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008810 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008811 SS.MakeTrivial(S.Context,
8812 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008813 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008814 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008815
Douglas Gregor06a9f362010-05-01 20:49:11 +00008816 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008817 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00008818 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8819 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008820 /*FirstQualifierInScope=*/0,
8821 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008822 /*TemplateArgs=*/0,
8823 /*SuppressQualifierCheck=*/true);
8824 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008825 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008826
Douglas Gregor06a9f362010-05-01 20:49:11 +00008827 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008828
Pavel Labath66ea35d2013-08-30 08:52:28 +00008829 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008830 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008831 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008832 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008833 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008834 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008835
Richard Smith8c889532012-11-14 00:50:40 +00008836 // If we built a call to a trivial 'operator=' while copying an array,
8837 // bail out. We'll replace the whole shebang with a memcpy.
8838 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8839 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8840 return StmtResult((Stmt*)0);
8841
Richard Smith044c8aa2012-11-13 00:54:12 +00008842 // Convert to an expression-statement, and clean up any produced
8843 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008844 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008845 }
John McCallb0207482010-03-16 06:11:48 +00008846
Richard Smith044c8aa2012-11-13 00:54:12 +00008847 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008848 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008849 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008850 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008851 ExprResult Assignment = S.CreateBuiltinBinOp(
8852 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008853 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008854 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008855 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008856 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008857
8858 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008859 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008860
Douglas Gregor06a9f362010-05-01 20:49:11 +00008861 // Construct a loop over the array bounds, e.g.,
8862 //
8863 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8864 //
8865 // that will copy each of the array elements.
8866 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008867
Douglas Gregor06a9f362010-05-01 20:49:11 +00008868 // Create the iteration variable.
8869 IdentifierInfo *IterationVarName = 0;
8870 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008871 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008872 llvm::raw_svector_ostream OS(Str);
8873 OS << "__i" << Depth;
8874 IterationVarName = &S.Context.Idents.get(OS.str());
8875 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008876 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008877 IterationVarName, SizeType,
8878 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008879 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008880
Douglas Gregor06a9f362010-05-01 20:49:11 +00008881 // Initialize the iteration variable to zero.
8882 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008883 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008884
Pavel Labath66ea35d2013-08-30 08:52:28 +00008885 // Creates a reference to the iteration variable.
8886 RefBuilder IterationVarRef(IterationVar, SizeType);
8887 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00008888
Douglas Gregor06a9f362010-05-01 20:49:11 +00008889 // Create the DeclStmt that holds the iteration variable.
8890 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008891
Douglas Gregor06a9f362010-05-01 20:49:11 +00008892 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008893 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
8894 MoveCastBuilder FromIndexMove(FromIndexCopy);
8895 const ExprBuilder *FromIndex;
8896 if (Copying)
8897 FromIndex = &FromIndexCopy;
8898 else
8899 FromIndex = &FromIndexMove;
8900
8901 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008902
8903 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008904 StmtResult Copy =
8905 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008906 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00008907 Copying, Depth + 1);
8908 // Bail out if copying fails or if we determined that we should use memcpy.
8909 if (Copy.isInvalid() || !Copy.get())
8910 return Copy;
8911
8912 // Create the comparison against the array bound.
8913 llvm::APInt Upper
8914 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8915 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00008916 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00008917 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8918 BO_NE, S.Context.BoolTy,
8919 VK_RValue, OK_Ordinary, Loc, false);
8920
8921 // Create the pre-increment of the iteration variable.
8922 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00008923 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
8924 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008925
Douglas Gregor06a9f362010-05-01 20:49:11 +00008926 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008927 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008928 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008929 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008930 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008931}
8932
Richard Smith8c889532012-11-14 00:50:40 +00008933static StmtResult
8934buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008935 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008936 bool CopyingBaseSubobject, bool Copying) {
8937 // Maybe we should use a memcpy?
8938 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8939 T.isTriviallyCopyableType(S.Context))
8940 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8941
8942 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8943 CopyingBaseSubobject,
8944 Copying, 0));
8945
8946 // If we ended up picking a trivial assignment operator for an array of a
8947 // non-trivially-copyable class type, just emit a memcpy.
8948 if (!Result.isInvalid() && !Result.get())
8949 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8950
8951 return Result;
8952}
8953
Richard Smithb9d0b762012-07-27 04:22:15 +00008954Sema::ImplicitExceptionSpecification
8955Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8956 CXXRecordDecl *ClassDecl = MD->getParent();
8957
8958 ImplicitExceptionSpecification ExceptSpec(*this);
8959 if (ClassDecl->isInvalidDecl())
8960 return ExceptSpec;
8961
8962 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8963 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8964 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8965
Douglas Gregorb87786f2010-07-01 17:48:08 +00008966 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008967 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008968 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008969
8970 // It is unspecified whether or not an implicit copy assignment operator
8971 // attempts to deduplicate calls to assignment operators of virtual bases are
8972 // made. As such, this exception specification is effectively unspecified.
8973 // Based on a similar decision made for constness in C++0x, we're erring on
8974 // the side of assuming such calls to be made regardless of whether they
8975 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008976 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8977 BaseEnd = ClassDecl->bases_end();
8978 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008979 if (Base->isVirtual())
8980 continue;
8981
Douglas Gregora376d102010-07-02 21:50:04 +00008982 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008983 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008984 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8985 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008986 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008987 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008988
8989 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8990 BaseEnd = ClassDecl->vbases_end();
8991 Base != BaseEnd; ++Base) {
8992 CXXRecordDecl *BaseClassDecl
8993 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8994 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8995 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008996 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008997 }
8998
Douglas Gregorb87786f2010-07-01 17:48:08 +00008999 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9000 FieldEnd = ClassDecl->field_end();
9001 Field != FieldEnd;
9002 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009003 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009004 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9005 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009006 LookupCopyingAssignment(FieldClassDecl,
9007 ArgQuals | FieldType.getCVRQualifiers(),
9008 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009009 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009010 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009011 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009012
Richard Smithb9d0b762012-07-27 04:22:15 +00009013 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009014}
9015
9016CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9017 // Note: The following rules are largely analoguous to the copy
9018 // constructor rules. Note that virtual bases are not taken into account
9019 // for determining the argument type of the operator. Note also that
9020 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009021 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009022
Richard Smithafb49182012-11-29 01:34:07 +00009023 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9024 if (DSM.isAlreadyBeingDeclared())
9025 return 0;
9026
Sean Hunt30de05c2011-05-14 05:23:20 +00009027 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9028 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009029 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9030 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009031 ArgType = ArgType.withConst();
9032 ArgType = Context.getLValueReferenceType(ArgType);
9033
Richard Smitha8942d72013-05-07 03:19:20 +00009034 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9035 CXXCopyAssignment,
9036 Const);
9037
Douglas Gregord3c35902010-07-01 16:36:15 +00009038 // An implicitly-declared copy assignment operator is an inline public
9039 // member of its class.
9040 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009041 SourceLocation ClassLoc = ClassDecl->getLocation();
9042 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009043 CXXMethodDecl *CopyAssignment =
9044 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9045 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9046 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009047 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009048 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009049 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009050
9051 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009052 FunctionProtoType::ExtProtoInfo EPI =
9053 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009054 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009055
Douglas Gregord3c35902010-07-01 16:36:15 +00009056 // Add the parameter to the operator.
9057 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009058 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009059 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009060 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009061 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009062
Richard Smithbc2a35d2012-12-08 08:32:28 +00009063 AddOverriddenMethods(ClassDecl, CopyAssignment);
9064
9065 CopyAssignment->setTrivial(
9066 ClassDecl->needsOverloadResolutionForCopyAssignment()
9067 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9068 : ClassDecl->hasTrivialCopyAssignment());
9069
Richard Smitha8942d72013-05-07 03:19:20 +00009070 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009071 // .... If the class definition does not explicitly declare a copy
9072 // assignment operator, there is no user-declared move constructor, and
9073 // there is no user-declared move assignment operator, a copy assignment
9074 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009075 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009076 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009077
Richard Smithbc2a35d2012-12-08 08:32:28 +00009078 // Note that we have added this copy-assignment operator.
9079 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9080
9081 if (Scope *S = getScopeForContext(ClassDecl))
9082 PushOnScopeChains(CopyAssignment, S, false);
9083 ClassDecl->addDecl(CopyAssignment);
9084
Douglas Gregord3c35902010-07-01 16:36:15 +00009085 return CopyAssignment;
9086}
9087
Richard Smith36155c12013-06-13 03:23:42 +00009088/// Diagnose an implicit copy operation for a class which is odr-used, but
9089/// which is deprecated because the class has a user-declared copy constructor,
9090/// copy assignment operator, or destructor.
9091static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9092 SourceLocation UseLoc) {
9093 assert(CopyOp->isImplicit());
9094
9095 CXXRecordDecl *RD = CopyOp->getParent();
9096 CXXMethodDecl *UserDeclaredOperation = 0;
9097
9098 // In Microsoft mode, assignment operations don't affect constructors and
9099 // vice versa.
9100 if (RD->hasUserDeclaredDestructor()) {
9101 UserDeclaredOperation = RD->getDestructor();
9102 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9103 RD->hasUserDeclaredCopyConstructor() &&
9104 !S.getLangOpts().MicrosoftMode) {
9105 // Find any user-declared copy constructor.
9106 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9107 E = RD->ctor_end(); I != E; ++I) {
9108 if (I->isCopyConstructor()) {
9109 UserDeclaredOperation = *I;
9110 break;
9111 }
9112 }
9113 assert(UserDeclaredOperation);
9114 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9115 RD->hasUserDeclaredCopyAssignment() &&
9116 !S.getLangOpts().MicrosoftMode) {
9117 // Find any user-declared move assignment operator.
9118 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9119 E = RD->method_end(); I != E; ++I) {
9120 if (I->isCopyAssignmentOperator()) {
9121 UserDeclaredOperation = *I;
9122 break;
9123 }
9124 }
9125 assert(UserDeclaredOperation);
9126 }
9127
9128 if (UserDeclaredOperation) {
9129 S.Diag(UserDeclaredOperation->getLocation(),
9130 diag::warn_deprecated_copy_operation)
9131 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9132 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9133 S.Diag(UseLoc, diag::note_member_synthesized_at)
9134 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9135 : Sema::CXXCopyAssignment)
9136 << RD;
9137 }
9138}
9139
Douglas Gregor06a9f362010-05-01 20:49:11 +00009140void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9141 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009142 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009143 CopyAssignOperator->isOverloadedOperator() &&
9144 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009145 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9146 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009147 "DefineImplicitCopyAssignment called for wrong function");
9148
9149 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9150
9151 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9152 CopyAssignOperator->setInvalidDecl();
9153 return;
9154 }
Richard Smith36155c12013-06-13 03:23:42 +00009155
9156 // C++11 [class.copy]p18:
9157 // The [definition of an implicitly declared copy assignment operator] is
9158 // deprecated if the class has a user-declared copy constructor or a
9159 // user-declared destructor.
9160 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9161 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9162
Eli Friedman86164e82013-09-05 00:02:25 +00009163 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009164
Eli Friedman9a14db32012-10-18 20:14:08 +00009165 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009166 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009167
9168 // C++0x [class.copy]p30:
9169 // The implicitly-defined or explicitly-defaulted copy assignment operator
9170 // for a non-union class X performs memberwise copy assignment of its
9171 // subobjects. The direct base classes of X are assigned first, in the
9172 // order of their declaration in the base-specifier-list, and then the
9173 // immediate non-static data members of X are assigned, in the order in
9174 // which they were declared in the class definition.
9175
9176 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009177 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009178
9179 // The parameter for the "other" object, which we are copying from.
9180 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9181 Qualifiers OtherQuals = Other->getType().getQualifiers();
9182 QualType OtherRefType = Other->getType();
9183 if (const LValueReferenceType *OtherRef
9184 = OtherRefType->getAs<LValueReferenceType>()) {
9185 OtherRefType = OtherRef->getPointeeType();
9186 OtherQuals = OtherRefType.getQualifiers();
9187 }
9188
9189 // Our location for everything implicitly-generated.
9190 SourceLocation Loc = CopyAssignOperator->getLocation();
9191
Pavel Labath66ea35d2013-08-30 08:52:28 +00009192 // Builds a DeclRefExpr for the "other" object.
9193 RefBuilder OtherRef(Other, OtherRefType);
9194
9195 // Builds the "this" pointer.
9196 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009197
9198 // Assign base classes.
9199 bool Invalid = false;
9200 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9201 E = ClassDecl->bases_end(); Base != E; ++Base) {
9202 // Form the assignment:
9203 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9204 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009205 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009206 Invalid = true;
9207 continue;
9208 }
9209
John McCallf871d0c2010-08-07 06:22:56 +00009210 CXXCastPath BasePath;
9211 BasePath.push_back(Base);
9212
Douglas Gregor06a9f362010-05-01 20:49:11 +00009213 // Construct the "from" expression, which is an implicit cast to the
9214 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009215 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9216 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009217
9218 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009219 DerefBuilder DerefThis(This);
9220 CastBuilder To(DerefThis,
9221 Context.getCVRQualifiedType(
9222 BaseType, CopyAssignOperator->getTypeQualifiers()),
9223 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009224
9225 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009226 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009227 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009228 /*CopyingBaseSubobject=*/true,
9229 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009230 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009231 Diag(CurrentLocation, diag::note_member_synthesized_at)
9232 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9233 CopyAssignOperator->setInvalidDecl();
9234 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009235 }
9236
9237 // Success! Record the copy.
9238 Statements.push_back(Copy.takeAs<Expr>());
9239 }
9240
Douglas Gregor06a9f362010-05-01 20:49:11 +00009241 // Assign non-static members.
9242 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9243 FieldEnd = ClassDecl->field_end();
9244 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009245 if (Field->isUnnamedBitfield())
9246 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009247
9248 if (Field->isInvalidDecl()) {
9249 Invalid = true;
9250 continue;
9251 }
9252
Douglas Gregor06a9f362010-05-01 20:49:11 +00009253 // Check for members of reference type; we can't copy those.
9254 if (Field->getType()->isReferenceType()) {
9255 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9256 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9257 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009258 Diag(CurrentLocation, diag::note_member_synthesized_at)
9259 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009260 Invalid = true;
9261 continue;
9262 }
9263
9264 // Check for members of const-qualified, non-class type.
9265 QualType BaseType = Context.getBaseElementType(Field->getType());
9266 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9267 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9268 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9269 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009270 Diag(CurrentLocation, diag::note_member_synthesized_at)
9271 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009272 Invalid = true;
9273 continue;
9274 }
John McCallb77115d2011-06-17 00:18:42 +00009275
9276 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009277 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9278 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009279
9280 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009281 if (FieldType->isIncompleteArrayType()) {
9282 assert(ClassDecl->hasFlexibleArrayMember() &&
9283 "Incomplete array type is not valid");
9284 continue;
9285 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009286
9287 // Build references to the field in the object we're copying from and to.
9288 CXXScopeSpec SS; // Intentionally empty
9289 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9290 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009291 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009292 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009293
9294 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9295
9296 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009297
Douglas Gregor06a9f362010-05-01 20:49:11 +00009298 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009299 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009300 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009301 /*CopyingBaseSubobject=*/false,
9302 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009303 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009304 Diag(CurrentLocation, diag::note_member_synthesized_at)
9305 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9306 CopyAssignOperator->setInvalidDecl();
9307 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009308 }
9309
9310 // Success! Record the copy.
9311 Statements.push_back(Copy.takeAs<Stmt>());
9312 }
9313
9314 if (!Invalid) {
9315 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009316 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009317
John McCall60d7b3a2010-08-24 06:29:42 +00009318 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009319 if (Return.isInvalid())
9320 Invalid = true;
9321 else {
9322 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009323
9324 if (Trap.hasErrorOccurred()) {
9325 Diag(CurrentLocation, diag::note_member_synthesized_at)
9326 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9327 Invalid = true;
9328 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009329 }
9330 }
9331
9332 if (Invalid) {
9333 CopyAssignOperator->setInvalidDecl();
9334 return;
9335 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009336
9337 StmtResult Body;
9338 {
9339 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009340 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009341 /*isStmtExpr=*/false);
9342 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9343 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009344 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009345
9346 if (ASTMutationListener *L = getASTMutationListener()) {
9347 L->CompletedImplicitDefinition(CopyAssignOperator);
9348 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009349}
9350
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009351Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009352Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9353 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009354
Richard Smithb9d0b762012-07-27 04:22:15 +00009355 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009356 if (ClassDecl->isInvalidDecl())
9357 return ExceptSpec;
9358
9359 // C++0x [except.spec]p14:
9360 // An implicitly declared special member function (Clause 12) shall have an
9361 // exception-specification. [...]
9362
9363 // It is unspecified whether or not an implicit move assignment operator
9364 // attempts to deduplicate calls to assignment operators of virtual bases are
9365 // made. As such, this exception specification is effectively unspecified.
9366 // Based on a similar decision made for constness in C++0x, we're erring on
9367 // the side of assuming such calls to be made regardless of whether they
9368 // actually happen.
9369 // Note that a move constructor is not implicitly declared when there are
9370 // virtual bases, but it can still be user-declared and explicitly defaulted.
9371 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9372 BaseEnd = ClassDecl->bases_end();
9373 Base != BaseEnd; ++Base) {
9374 if (Base->isVirtual())
9375 continue;
9376
9377 CXXRecordDecl *BaseClassDecl
9378 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9379 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009380 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009381 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382 }
9383
9384 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9385 BaseEnd = ClassDecl->vbases_end();
9386 Base != BaseEnd; ++Base) {
9387 CXXRecordDecl *BaseClassDecl
9388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9389 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009390 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009391 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009392 }
9393
9394 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9395 FieldEnd = ClassDecl->field_end();
9396 Field != FieldEnd;
9397 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009398 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009399 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009400 if (CXXMethodDecl *MoveAssign =
9401 LookupMovingAssignment(FieldClassDecl,
9402 FieldType.getCVRQualifiers(),
9403 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009404 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009405 }
9406 }
9407
9408 return ExceptSpec;
9409}
9410
Richard Smith1c931be2012-04-02 18:40:40 +00009411/// Determine whether the class type has any direct or indirect virtual base
9412/// classes which have a non-trivial move assignment operator.
9413static bool
9414hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9415 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9416 BaseEnd = ClassDecl->vbases_end();
9417 Base != BaseEnd; ++Base) {
9418 CXXRecordDecl *BaseClass =
9419 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9420
9421 // Try to declare the move assignment. If it would be deleted, then the
9422 // class does not have a non-trivial move assignment.
9423 if (BaseClass->needsImplicitMoveAssignment())
9424 S.DeclareImplicitMoveAssignment(BaseClass);
9425
Richard Smith426391c2012-11-16 00:53:38 +00009426 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009427 return true;
9428 }
9429
9430 return false;
9431}
9432
9433/// Determine whether the given type either has a move constructor or is
9434/// trivially copyable.
9435static bool
9436hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9437 Type = S.Context.getBaseElementType(Type);
9438
9439 // FIXME: Technically, non-trivially-copyable non-class types, such as
9440 // reference types, are supposed to return false here, but that appears
9441 // to be a standard defect.
9442 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009443 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009444 return true;
9445
9446 if (Type.isTriviallyCopyableType(S.Context))
9447 return true;
9448
9449 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009450 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9451 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009452 if (ClassDecl->needsImplicitMoveConstructor())
9453 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009454 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009455 }
9456
Richard Smithe5411b72012-12-01 02:35:44 +00009457 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9458 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009459 if (ClassDecl->needsImplicitMoveAssignment())
9460 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009461 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009462}
9463
9464/// Determine whether all non-static data members and direct or virtual bases
9465/// of class \p ClassDecl have either a move operation, or are trivially
9466/// copyable.
9467static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9468 bool IsConstructor) {
9469 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9470 BaseEnd = ClassDecl->bases_end();
9471 Base != BaseEnd; ++Base) {
9472 if (Base->isVirtual())
9473 continue;
9474
9475 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9476 return false;
9477 }
9478
9479 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9480 BaseEnd = ClassDecl->vbases_end();
9481 Base != BaseEnd; ++Base) {
9482 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9483 return false;
9484 }
9485
9486 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9487 FieldEnd = ClassDecl->field_end();
9488 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009489 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009490 return false;
9491 }
9492
9493 return true;
9494}
9495
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009496CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009497 // C++11 [class.copy]p20:
9498 // If the definition of a class X does not explicitly declare a move
9499 // assignment operator, one will be implicitly declared as defaulted
9500 // if and only if:
9501 //
9502 // - [first 4 bullets]
9503 assert(ClassDecl->needsImplicitMoveAssignment());
9504
Richard Smithafb49182012-11-29 01:34:07 +00009505 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9506 if (DSM.isAlreadyBeingDeclared())
9507 return 0;
9508
Richard Smith1c931be2012-04-02 18:40:40 +00009509 // [Checked after we build the declaration]
9510 // - the move assignment operator would not be implicitly defined as
9511 // deleted,
9512
9513 // [DR1402]:
9514 // - X has no direct or indirect virtual base class with a non-trivial
9515 // move assignment operator, and
9516 // - each of X's non-static data members and direct or virtual base classes
9517 // has a type that either has a move assignment operator or is trivially
9518 // copyable.
9519 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9520 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9521 ClassDecl->setFailedImplicitMoveAssignment();
9522 return 0;
9523 }
9524
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009525 // Note: The following rules are largely analoguous to the move
9526 // constructor rules.
9527
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009528 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9529 QualType RetType = Context.getLValueReferenceType(ArgType);
9530 ArgType = Context.getRValueReferenceType(ArgType);
9531
Richard Smitha8942d72013-05-07 03:19:20 +00009532 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9533 CXXMoveAssignment,
9534 false);
9535
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009536 // An implicitly-declared move assignment operator is an inline public
9537 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009538 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9539 SourceLocation ClassLoc = ClassDecl->getLocation();
9540 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009541 CXXMethodDecl *MoveAssignment =
9542 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9543 /*TInfo=*/0, /*StorageClass=*/SC_None,
9544 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009545 MoveAssignment->setAccess(AS_public);
9546 MoveAssignment->setDefaulted();
9547 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009548
Richard Smithb9d0b762012-07-27 04:22:15 +00009549 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009550 FunctionProtoType::ExtProtoInfo EPI =
9551 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009552 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009553
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009554 // Add the parameter to the operator.
9555 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9556 ClassLoc, ClassLoc, /*Id=*/0,
9557 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009558 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009559 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009560
Richard Smithbc2a35d2012-12-08 08:32:28 +00009561 AddOverriddenMethods(ClassDecl, MoveAssignment);
9562
9563 MoveAssignment->setTrivial(
9564 ClassDecl->needsOverloadResolutionForMoveAssignment()
9565 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9566 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009567
9568 // C++0x [class.copy]p9:
9569 // If the definition of a class X does not explicitly declare a move
9570 // assignment operator, one will be implicitly declared as defaulted if and
9571 // only if:
9572 // [...]
9573 // - the move assignment operator would not be implicitly defined as
9574 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009575 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009576 // Cache this result so that we don't try to generate this over and over
9577 // on every lookup, leaking memory and wasting time.
9578 ClassDecl->setFailedImplicitMoveAssignment();
9579 return 0;
9580 }
9581
Richard Smithbc2a35d2012-12-08 08:32:28 +00009582 // Note that we have added this copy-assignment operator.
9583 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9584
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009585 if (Scope *S = getScopeForContext(ClassDecl))
9586 PushOnScopeChains(MoveAssignment, S, false);
9587 ClassDecl->addDecl(MoveAssignment);
9588
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009589 return MoveAssignment;
9590}
9591
9592void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9593 CXXMethodDecl *MoveAssignOperator) {
9594 assert((MoveAssignOperator->isDefaulted() &&
9595 MoveAssignOperator->isOverloadedOperator() &&
9596 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009597 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9598 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009599 "DefineImplicitMoveAssignment called for wrong function");
9600
9601 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9602
9603 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9604 MoveAssignOperator->setInvalidDecl();
9605 return;
9606 }
9607
Eli Friedman86164e82013-09-05 00:02:25 +00009608 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009609
Eli Friedman9a14db32012-10-18 20:14:08 +00009610 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009611 DiagnosticErrorTrap Trap(Diags);
9612
9613 // C++0x [class.copy]p28:
9614 // The implicitly-defined or move assignment operator for a non-union class
9615 // X performs memberwise move assignment of its subobjects. The direct base
9616 // classes of X are assigned first, in the order of their declaration in the
9617 // base-specifier-list, and then the immediate non-static data members of X
9618 // are assigned, in the order in which they were declared in the class
9619 // definition.
9620
9621 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009622 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009623
9624 // The parameter for the "other" object, which we are move from.
9625 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9626 QualType OtherRefType = Other->getType()->
9627 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009628 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009629 "Bad argument type of defaulted move assignment");
9630
9631 // Our location for everything implicitly-generated.
9632 SourceLocation Loc = MoveAssignOperator->getLocation();
9633
Pavel Labath66ea35d2013-08-30 08:52:28 +00009634 // Builds a reference to the "other" object.
9635 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009636 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009637 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009638
Pavel Labath66ea35d2013-08-30 08:52:28 +00009639 // Builds the "this" pointer.
9640 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009641
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009642 // Assign base classes.
9643 bool Invalid = false;
9644 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9645 E = ClassDecl->bases_end(); Base != E; ++Base) {
9646 // Form the assignment:
9647 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9648 QualType BaseType = Base->getType().getUnqualifiedType();
9649 if (!BaseType->isRecordType()) {
9650 Invalid = true;
9651 continue;
9652 }
9653
9654 CXXCastPath BasePath;
9655 BasePath.push_back(Base);
9656
9657 // Construct the "from" expression, which is an implicit cast to the
9658 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009659 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009660
9661 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009662 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009663
9664 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009665 CastBuilder To(DerefThis,
9666 Context.getCVRQualifiedType(
9667 BaseType, MoveAssignOperator->getTypeQualifiers()),
9668 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009669
9670 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009671 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009672 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009673 /*CopyingBaseSubobject=*/true,
9674 /*Copying=*/false);
9675 if (Move.isInvalid()) {
9676 Diag(CurrentLocation, diag::note_member_synthesized_at)
9677 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9678 MoveAssignOperator->setInvalidDecl();
9679 return;
9680 }
9681
9682 // Success! Record the move.
9683 Statements.push_back(Move.takeAs<Expr>());
9684 }
9685
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009686 // Assign non-static members.
9687 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9688 FieldEnd = ClassDecl->field_end();
9689 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009690 if (Field->isUnnamedBitfield())
9691 continue;
9692
Eli Friedman8150da32013-06-07 01:48:56 +00009693 if (Field->isInvalidDecl()) {
9694 Invalid = true;
9695 continue;
9696 }
9697
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009698 // Check for members of reference type; we can't move those.
9699 if (Field->getType()->isReferenceType()) {
9700 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9701 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9702 Diag(Field->getLocation(), diag::note_declared_at);
9703 Diag(CurrentLocation, diag::note_member_synthesized_at)
9704 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9705 Invalid = true;
9706 continue;
9707 }
9708
9709 // Check for members of const-qualified, non-class type.
9710 QualType BaseType = Context.getBaseElementType(Field->getType());
9711 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9712 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9713 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9714 Diag(Field->getLocation(), diag::note_declared_at);
9715 Diag(CurrentLocation, diag::note_member_synthesized_at)
9716 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9717 Invalid = true;
9718 continue;
9719 }
9720
9721 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009722 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9723 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009724
9725 QualType FieldType = Field->getType().getNonReferenceType();
9726 if (FieldType->isIncompleteArrayType()) {
9727 assert(ClassDecl->hasFlexibleArrayMember() &&
9728 "Incomplete array type is not valid");
9729 continue;
9730 }
9731
9732 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009733 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9734 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009735 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009736 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009737 MemberBuilder From(MoveOther, OtherRefType,
9738 /*IsArrow=*/false, MemberLookup);
9739 MemberBuilder To(This, getCurrentThisType(),
9740 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009741
Pavel Labath66ea35d2013-08-30 08:52:28 +00009742 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009743 "Member reference with rvalue base must be rvalue except for reference "
9744 "members, which aren't allowed for move assignment.");
9745
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009746 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009747 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009748 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009749 /*CopyingBaseSubobject=*/false,
9750 /*Copying=*/false);
9751 if (Move.isInvalid()) {
9752 Diag(CurrentLocation, diag::note_member_synthesized_at)
9753 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9754 MoveAssignOperator->setInvalidDecl();
9755 return;
9756 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009757
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009758 // Success! Record the copy.
9759 Statements.push_back(Move.takeAs<Stmt>());
9760 }
9761
9762 if (!Invalid) {
9763 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009764 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009765
9766 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9767 if (Return.isInvalid())
9768 Invalid = true;
9769 else {
9770 Statements.push_back(Return.takeAs<Stmt>());
9771
9772 if (Trap.hasErrorOccurred()) {
9773 Diag(CurrentLocation, diag::note_member_synthesized_at)
9774 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9775 Invalid = true;
9776 }
9777 }
9778 }
9779
9780 if (Invalid) {
9781 MoveAssignOperator->setInvalidDecl();
9782 return;
9783 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009784
9785 StmtResult Body;
9786 {
9787 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009788 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009789 /*isStmtExpr=*/false);
9790 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9791 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009792 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9793
9794 if (ASTMutationListener *L = getASTMutationListener()) {
9795 L->CompletedImplicitDefinition(MoveAssignOperator);
9796 }
9797}
9798
Richard Smithb9d0b762012-07-27 04:22:15 +00009799Sema::ImplicitExceptionSpecification
9800Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9801 CXXRecordDecl *ClassDecl = MD->getParent();
9802
9803 ImplicitExceptionSpecification ExceptSpec(*this);
9804 if (ClassDecl->isInvalidDecl())
9805 return ExceptSpec;
9806
9807 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9808 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9809 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9810
Douglas Gregor0d405db2010-07-01 20:59:04 +00009811 // C++ [except.spec]p14:
9812 // An implicitly declared special member function (Clause 12) shall have an
9813 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009814 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9815 BaseEnd = ClassDecl->bases_end();
9816 Base != BaseEnd;
9817 ++Base) {
9818 // Virtual bases are handled below.
9819 if (Base->isVirtual())
9820 continue;
9821
Douglas Gregor22584312010-07-02 23:41:54 +00009822 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009823 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009824 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009825 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009826 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009827 }
9828 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9829 BaseEnd = ClassDecl->vbases_end();
9830 Base != BaseEnd;
9831 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009832 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009833 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009834 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009835 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009836 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009837 }
9838 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9839 FieldEnd = ClassDecl->field_end();
9840 Field != FieldEnd;
9841 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009842 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009843 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9844 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009845 LookupCopyingConstructor(FieldClassDecl,
9846 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009847 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009848 }
9849 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009850
Richard Smithb9d0b762012-07-27 04:22:15 +00009851 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009852}
9853
9854CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9855 CXXRecordDecl *ClassDecl) {
9856 // C++ [class.copy]p4:
9857 // If the class definition does not explicitly declare a copy
9858 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009859 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009860
Richard Smithafb49182012-11-29 01:34:07 +00009861 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9862 if (DSM.isAlreadyBeingDeclared())
9863 return 0;
9864
Sean Hunt49634cf2011-05-13 06:10:58 +00009865 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9866 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009867 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009868 if (Const)
9869 ArgType = ArgType.withConst();
9870 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009871
Richard Smith7756afa2012-06-10 05:43:50 +00009872 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9873 CXXCopyConstructor,
9874 Const);
9875
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009876 DeclarationName Name
9877 = Context.DeclarationNames.getCXXConstructorName(
9878 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009879 SourceLocation ClassLoc = ClassDecl->getLocation();
9880 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009881
9882 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009883 // member of its class.
9884 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009885 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009886 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009887 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009888 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009889 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009890
Richard Smithb9d0b762012-07-27 04:22:15 +00009891 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009892 FunctionProtoType::ExtProtoInfo EPI =
9893 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +00009894 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009895 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009896
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009897 // Add the parameter to the constructor.
9898 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009899 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009900 /*IdentifierInfo=*/0,
9901 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009902 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009903 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009904
Richard Smithbc2a35d2012-12-08 08:32:28 +00009905 CopyConstructor->setTrivial(
9906 ClassDecl->needsOverloadResolutionForCopyConstructor()
9907 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9908 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009909
Nico Weberafcc96a2012-01-23 03:19:29 +00009910 // C++11 [class.copy]p8:
9911 // ... If the class definition does not explicitly declare a copy
9912 // constructor, there is no user-declared move constructor, and there is no
9913 // user-declared move assignment operator, a copy constructor is implicitly
9914 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009915 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009916 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009917
Richard Smithbc2a35d2012-12-08 08:32:28 +00009918 // Note that we have declared this constructor.
9919 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9920
9921 if (Scope *S = getScopeForContext(ClassDecl))
9922 PushOnScopeChains(CopyConstructor, S, false);
9923 ClassDecl->addDecl(CopyConstructor);
9924
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009925 return CopyConstructor;
9926}
9927
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009928void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009929 CXXConstructorDecl *CopyConstructor) {
9930 assert((CopyConstructor->isDefaulted() &&
9931 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009932 !CopyConstructor->doesThisDeclarationHaveABody() &&
9933 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009934 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009935
Anders Carlsson63010a72010-04-23 16:24:12 +00009936 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009937 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009938
Richard Smith36155c12013-06-13 03:23:42 +00009939 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +00009940 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +00009941 // deprecated if the class has a user-declared copy assignment operator
9942 // or a user-declared destructor.
9943 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9944 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9945
Eli Friedman9a14db32012-10-18 20:14:08 +00009946 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009947 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009948
David Blaikie93c86172013-01-17 05:26:25 +00009949 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009950 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009951 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009952 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009953 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009954 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009955 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009956 CopyConstructor->setBody(ActOnCompoundStmt(
9957 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
9958 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009959 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009960
Eli Friedman86164e82013-09-05 00:02:25 +00009961 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009962 if (ASTMutationListener *L = getASTMutationListener()) {
9963 L->CompletedImplicitDefinition(CopyConstructor);
9964 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009965}
9966
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009967Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009968Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9969 CXXRecordDecl *ClassDecl = MD->getParent();
9970
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009971 // C++ [except.spec]p14:
9972 // An implicitly declared special member function (Clause 12) shall have an
9973 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009974 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009975 if (ClassDecl->isInvalidDecl())
9976 return ExceptSpec;
9977
9978 // Direct base-class constructors.
9979 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9980 BEnd = ClassDecl->bases_end();
9981 B != BEnd; ++B) {
9982 if (B->isVirtual()) // Handled below.
9983 continue;
9984
9985 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9986 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009987 CXXConstructorDecl *Constructor =
9988 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009989 // If this is a deleted function, add it anyway. This might be conformant
9990 // with the standard. This might not. I'm not sure. It might not matter.
9991 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009992 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009993 }
9994 }
9995
9996 // Virtual base-class constructors.
9997 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9998 BEnd = ClassDecl->vbases_end();
9999 B != BEnd; ++B) {
10000 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10001 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010002 CXXConstructorDecl *Constructor =
10003 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010004 // If this is a deleted function, add it anyway. This might be conformant
10005 // with the standard. This might not. I'm not sure. It might not matter.
10006 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010007 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010008 }
10009 }
10010
10011 // Field constructors.
10012 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10013 FEnd = ClassDecl->field_end();
10014 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010015 QualType FieldType = Context.getBaseElementType(F->getType());
10016 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10017 CXXConstructorDecl *Constructor =
10018 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010019 // If this is a deleted function, add it anyway. This might be conformant
10020 // with the standard. This might not. I'm not sure. It might not matter.
10021 // In particular, the problem is that this function never gets called. It
10022 // might just be ill-formed because this function attempts to refer to
10023 // a deleted function here.
10024 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010025 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010026 }
10027 }
10028
10029 return ExceptSpec;
10030}
10031
10032CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10033 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010034 // C++11 [class.copy]p9:
10035 // If the definition of a class X does not explicitly declare a move
10036 // constructor, one will be implicitly declared as defaulted if and only if:
10037 //
10038 // - [first 4 bullets]
10039 assert(ClassDecl->needsImplicitMoveConstructor());
10040
Richard Smithafb49182012-11-29 01:34:07 +000010041 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10042 if (DSM.isAlreadyBeingDeclared())
10043 return 0;
10044
Richard Smith1c931be2012-04-02 18:40:40 +000010045 // [Checked after we build the declaration]
10046 // - the move assignment operator would not be implicitly defined as
10047 // deleted,
10048
10049 // [DR1402]:
10050 // - each of X's non-static data members and direct or virtual base classes
10051 // has a type that either has a move constructor or is trivially copyable.
10052 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10053 ClassDecl->setFailedImplicitMoveConstructor();
10054 return 0;
10055 }
10056
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010057 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10058 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010059
Richard Smith7756afa2012-06-10 05:43:50 +000010060 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10061 CXXMoveConstructor,
10062 false);
10063
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010064 DeclarationName Name
10065 = Context.DeclarationNames.getCXXConstructorName(
10066 Context.getCanonicalType(ClassType));
10067 SourceLocation ClassLoc = ClassDecl->getLocation();
10068 DeclarationNameInfo NameInfo(Name, ClassLoc);
10069
Richard Smitha8942d72013-05-07 03:19:20 +000010070 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010071 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010072 // member of its class.
10073 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010074 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010075 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010076 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010077 MoveConstructor->setAccess(AS_public);
10078 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010079
Richard Smithb9d0b762012-07-27 04:22:15 +000010080 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010081 FunctionProtoType::ExtProtoInfo EPI =
10082 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010083 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010084 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010085
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010086 // Add the parameter to the constructor.
10087 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10088 ClassLoc, ClassLoc,
10089 /*IdentifierInfo=*/0,
10090 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010091 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010092 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010093
Richard Smithbc2a35d2012-12-08 08:32:28 +000010094 MoveConstructor->setTrivial(
10095 ClassDecl->needsOverloadResolutionForMoveConstructor()
10096 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10097 : ClassDecl->hasTrivialMoveConstructor());
10098
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010099 // C++0x [class.copy]p9:
10100 // If the definition of a class X does not explicitly declare a move
10101 // constructor, one will be implicitly declared as defaulted if and only if:
10102 // [...]
10103 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010104 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010105 // Cache this result so that we don't try to generate this over and over
10106 // on every lookup, leaking memory and wasting time.
10107 ClassDecl->setFailedImplicitMoveConstructor();
10108 return 0;
10109 }
10110
10111 // Note that we have declared this constructor.
10112 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10113
10114 if (Scope *S = getScopeForContext(ClassDecl))
10115 PushOnScopeChains(MoveConstructor, S, false);
10116 ClassDecl->addDecl(MoveConstructor);
10117
10118 return MoveConstructor;
10119}
10120
10121void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10122 CXXConstructorDecl *MoveConstructor) {
10123 assert((MoveConstructor->isDefaulted() &&
10124 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010125 !MoveConstructor->doesThisDeclarationHaveABody() &&
10126 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010127 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10128
10129 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10130 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10131
Eli Friedman9a14db32012-10-18 20:14:08 +000010132 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010133 DiagnosticErrorTrap Trap(Diags);
10134
David Blaikie93c86172013-01-17 05:26:25 +000010135 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010136 Trap.hasErrorOccurred()) {
10137 Diag(CurrentLocation, diag::note_member_synthesized_at)
10138 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10139 MoveConstructor->setInvalidDecl();
10140 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010141 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010142 MoveConstructor->setBody(ActOnCompoundStmt(
10143 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10144 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010145 }
10146
Eli Friedman86164e82013-09-05 00:02:25 +000010147 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010148
10149 if (ASTMutationListener *L = getASTMutationListener()) {
10150 L->CompletedImplicitDefinition(MoveConstructor);
10151 }
10152}
10153
Douglas Gregore4e68d42012-02-15 19:33:52 +000010154bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010155 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010156}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010157
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010158/// \brief Mark the call operator of the given lambda closure type as "used".
10159static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10160 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010161 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010162 Lambda->lookup(
10163 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010164 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +000010165 CallOperator->markUsed(S.Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010166}
10167
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010168void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10169 SourceLocation CurrentLocation,
10170 CXXConversionDecl *Conv)
10171{
Manuel Klimek152b4e42013-08-22 12:12:24 +000010172 CXXRecordDecl *Lambda = Conv->getParent();
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010173
10174 // Make sure that the lambda call operator is marked used.
Manuel Klimek152b4e42013-08-22 12:12:24 +000010175 markLambdaCallOperatorUsed(*this, Lambda);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010176
Eli Friedman86164e82013-09-05 00:02:25 +000010177 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010178
Eli Friedman9a14db32012-10-18 20:14:08 +000010179 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010180 DiagnosticErrorTrap Trap(Diags);
10181
Manuel Klimek152b4e42013-08-22 12:12:24 +000010182 // Return the address of the __invoke function.
10183 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10184 CXXMethodDecl *Invoke
10185 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010186 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10187 VK_LValue, Conv->getLocation()).take();
Manuel Klimek152b4e42013-08-22 12:12:24 +000010188 assert(FunctionRef && "Can't refer to __invoke function?");
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010189 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010190 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010191 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010192 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010193
Manuel Klimek152b4e42013-08-22 12:12:24 +000010194 // Fill in the __invoke function with a dummy implementation. IR generation
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010195 // will fill in the actual details.
Eli Friedman86164e82013-09-05 00:02:25 +000010196 Invoke->markUsed(Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010197 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010198 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010199
10200 if (ASTMutationListener *L = getASTMutationListener()) {
10201 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010202 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010203 }
10204}
10205
10206void Sema::DefineImplicitLambdaToBlockPointerConversion(
10207 SourceLocation CurrentLocation,
10208 CXXConversionDecl *Conv)
10209{
Eli Friedman86164e82013-09-05 00:02:25 +000010210 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010211
Eli Friedman9a14db32012-10-18 20:14:08 +000010212 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010213 DiagnosticErrorTrap Trap(Diags);
10214
Douglas Gregorac1303e2012-02-22 05:02:47 +000010215 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010216 Expr *This = ActOnCXXThis(CurrentLocation).take();
10217 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010218
Eli Friedman23f02672012-03-01 04:01:32 +000010219 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10220 Conv->getLocation(),
10221 Conv, DerefThis);
10222
10223 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10224 // behavior. Note that only the general conversion function does this
10225 // (since it's unusable otherwise); in the case where we inline the
10226 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010227 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010228 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10229 CK_CopyAndAutoreleaseBlockObject,
10230 BuildBlock.get(), 0, VK_RValue);
10231
10232 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010233 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010234 Conv->setInvalidDecl();
10235 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010236 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010237
Douglas Gregorac1303e2012-02-22 05:02:47 +000010238 // Create the return statement that returns the block from the conversion
10239 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010240 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010241 if (Return.isInvalid()) {
10242 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10243 Conv->setInvalidDecl();
10244 return;
10245 }
10246
10247 // Set the body of the conversion function.
10248 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010249 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010250 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010251 Conv->getLocation()));
10252
Douglas Gregorac1303e2012-02-22 05:02:47 +000010253 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010254 if (ASTMutationListener *L = getASTMutationListener()) {
10255 L->CompletedImplicitDefinition(Conv);
10256 }
10257}
10258
Douglas Gregorf52757d2012-03-10 06:53:13 +000010259/// \brief Determine whether the given list arguments contains exactly one
10260/// "real" (non-default) argument.
10261static bool hasOneRealArgument(MultiExprArg Args) {
10262 switch (Args.size()) {
10263 case 0:
10264 return false;
10265
10266 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010267 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010268 return false;
10269
10270 // fall through
10271 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010272 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010273 }
10274
10275 return false;
10276}
10277
John McCall60d7b3a2010-08-24 06:29:42 +000010278ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010279Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010280 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010281 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010282 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010283 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010284 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010285 unsigned ConstructKind,
10286 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010287 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010288
Douglas Gregor2f599792010-04-02 18:24:57 +000010289 // C++0x [class.copy]p34:
10290 // When certain criteria are met, an implementation is allowed to
10291 // omit the copy/move construction of a class object, even if the
10292 // copy/move constructor and/or destructor for the object have
10293 // side effects. [...]
10294 // - when a temporary class object that has not been bound to a
10295 // reference (12.2) would be copied/moved to a class object
10296 // with the same cv-unqualified type, the copy/move operation
10297 // can be omitted by constructing the temporary object
10298 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010299 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010300 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010301 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010302 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010303 }
Mike Stump1eb44332009-09-09 15:08:12 +000010304
10305 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010306 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010307 IsListInitialization, RequiresZeroInit,
10308 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010309}
10310
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010311/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10312/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010313ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010314Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10315 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010316 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010317 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010318 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010319 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010320 unsigned ConstructKind,
10321 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010322 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010323 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010324 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010325 HadMultipleCandidates,
10326 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010327 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10328 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010329}
10330
John McCall68c6c9a2010-02-02 09:10:11 +000010331void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010332 if (VD->isInvalidDecl()) return;
10333
John McCall68c6c9a2010-02-02 09:10:11 +000010334 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010335 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010336 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010337 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010338
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010339 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010340 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010341 CheckDestructorAccess(VD->getLocation(), Destructor,
10342 PDiag(diag::err_access_dtor_var)
10343 << VD->getDeclName()
10344 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010345 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010346
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010347 if (!VD->hasGlobalStorage()) return;
10348
10349 // Emit warning for non-trivial dtor in global scope (a real global,
10350 // class-static, function-static).
10351 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10352
10353 // TODO: this should be re-enabled for static locals by !CXAAtExit
10354 if (!VD->isStaticLocal())
10355 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010356}
10357
Douglas Gregor39da0b82009-09-09 23:08:42 +000010358/// \brief Given a constructor and the set of arguments provided for the
10359/// constructor, convert the arguments and add any required default arguments
10360/// to form a proper call to this constructor.
10361///
10362/// \returns true if an error occurred, false otherwise.
10363bool
10364Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10365 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010366 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010367 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010368 bool AllowExplicit,
10369 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010370 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10371 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010372 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010373
10374 const FunctionProtoType *Proto
10375 = Constructor->getType()->getAs<FunctionProtoType>();
10376 assert(Proto && "Constructor without a prototype?");
10377 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010378
10379 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010380 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010381 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010382 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010383 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010384
10385 VariadicCallType CallType =
10386 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010387 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010388 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010389 Proto, 0,
10390 llvm::makeArrayRef(Args, NumArgs),
10391 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010392 CallType, AllowExplicit,
10393 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010394 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010395
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010396 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010397
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010398 CheckConstructorCall(Constructor,
10399 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10400 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010401 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010402
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010403 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010404}
10405
Anders Carlsson20d45d22009-12-12 00:32:00 +000010406static inline bool
10407CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10408 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010409 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010410 if (isa<NamespaceDecl>(DC)) {
10411 return SemaRef.Diag(FnDecl->getLocation(),
10412 diag::err_operator_new_delete_declared_in_namespace)
10413 << FnDecl->getDeclName();
10414 }
10415
10416 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010417 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010418 return SemaRef.Diag(FnDecl->getLocation(),
10419 diag::err_operator_new_delete_declared_static)
10420 << FnDecl->getDeclName();
10421 }
10422
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010423 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010424}
10425
Anders Carlsson156c78e2009-12-13 17:53:43 +000010426static inline bool
10427CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10428 CanQualType ExpectedResultType,
10429 CanQualType ExpectedFirstParamType,
10430 unsigned DependentParamTypeDiag,
10431 unsigned InvalidParamTypeDiag) {
10432 QualType ResultType =
10433 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10434
10435 // Check that the result type is not dependent.
10436 if (ResultType->isDependentType())
10437 return SemaRef.Diag(FnDecl->getLocation(),
10438 diag::err_operator_new_delete_dependent_result_type)
10439 << FnDecl->getDeclName() << ExpectedResultType;
10440
10441 // Check that the result type is what we expect.
10442 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10443 return SemaRef.Diag(FnDecl->getLocation(),
10444 diag::err_operator_new_delete_invalid_result_type)
10445 << FnDecl->getDeclName() << ExpectedResultType;
10446
10447 // A function template must have at least 2 parameters.
10448 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10449 return SemaRef.Diag(FnDecl->getLocation(),
10450 diag::err_operator_new_delete_template_too_few_parameters)
10451 << FnDecl->getDeclName();
10452
10453 // The function decl must have at least 1 parameter.
10454 if (FnDecl->getNumParams() == 0)
10455 return SemaRef.Diag(FnDecl->getLocation(),
10456 diag::err_operator_new_delete_too_few_parameters)
10457 << FnDecl->getDeclName();
10458
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010459 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010460 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10461 if (FirstParamType->isDependentType())
10462 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10463 << FnDecl->getDeclName() << ExpectedFirstParamType;
10464
10465 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010466 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010467 ExpectedFirstParamType)
10468 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10469 << FnDecl->getDeclName() << ExpectedFirstParamType;
10470
10471 return false;
10472}
10473
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010474static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010475CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010476 // C++ [basic.stc.dynamic.allocation]p1:
10477 // A program is ill-formed if an allocation function is declared in a
10478 // namespace scope other than global scope or declared static in global
10479 // scope.
10480 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10481 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010482
10483 CanQualType SizeTy =
10484 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10485
10486 // C++ [basic.stc.dynamic.allocation]p1:
10487 // The return type shall be void*. The first parameter shall have type
10488 // std::size_t.
10489 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10490 SizeTy,
10491 diag::err_operator_new_dependent_param_type,
10492 diag::err_operator_new_param_type))
10493 return true;
10494
10495 // C++ [basic.stc.dynamic.allocation]p1:
10496 // The first parameter shall not have an associated default argument.
10497 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010498 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010499 diag::err_operator_new_default_arg)
10500 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10501
10502 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010503}
10504
10505static bool
Richard Smith444d3842012-10-20 08:26:51 +000010506CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010507 // C++ [basic.stc.dynamic.deallocation]p1:
10508 // A program is ill-formed if deallocation functions are declared in a
10509 // namespace scope other than global scope or declared static in global
10510 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010511 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10512 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010513
10514 // C++ [basic.stc.dynamic.deallocation]p2:
10515 // Each deallocation function shall return void and its first parameter
10516 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010517 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10518 SemaRef.Context.VoidPtrTy,
10519 diag::err_operator_delete_dependent_param_type,
10520 diag::err_operator_delete_param_type))
10521 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010522
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010523 return false;
10524}
10525
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010526/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10527/// of this overloaded operator is well-formed. If so, returns false;
10528/// otherwise, emits appropriate diagnostics and returns true.
10529bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010530 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010531 "Expected an overloaded operator declaration");
10532
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010533 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10534
Mike Stump1eb44332009-09-09 15:08:12 +000010535 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010536 // The allocation and deallocation functions, operator new,
10537 // operator new[], operator delete and operator delete[], are
10538 // described completely in 3.7.3. The attributes and restrictions
10539 // found in the rest of this subclause do not apply to them unless
10540 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010541 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010542 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010543
Anders Carlssona3ccda52009-12-12 00:26:23 +000010544 if (Op == OO_New || Op == OO_Array_New)
10545 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010546
10547 // C++ [over.oper]p6:
10548 // An operator function shall either be a non-static member
10549 // function or be a non-member function and have at least one
10550 // parameter whose type is a class, a reference to a class, an
10551 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010552 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10553 if (MethodDecl->isStatic())
10554 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010555 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010556 } else {
10557 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010558 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10559 ParamEnd = FnDecl->param_end();
10560 Param != ParamEnd; ++Param) {
10561 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010562 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10563 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010564 ClassOrEnumParam = true;
10565 break;
10566 }
10567 }
10568
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010569 if (!ClassOrEnumParam)
10570 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010571 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010572 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010573 }
10574
10575 // C++ [over.oper]p8:
10576 // An operator function cannot have default arguments (8.3.6),
10577 // except where explicitly stated below.
10578 //
Mike Stump1eb44332009-09-09 15:08:12 +000010579 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010580 // (C++ [over.call]p1).
10581 if (Op != OO_Call) {
10582 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10583 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010584 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010585 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010586 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010587 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010588 }
10589 }
10590
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010591 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10592 { false, false, false }
10593#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10594 , { Unary, Binary, MemberOnly }
10595#include "clang/Basic/OperatorKinds.def"
10596 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010597
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010598 bool CanBeUnaryOperator = OperatorUses[Op][0];
10599 bool CanBeBinaryOperator = OperatorUses[Op][1];
10600 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010601
10602 // C++ [over.oper]p8:
10603 // [...] Operator functions cannot have more or fewer parameters
10604 // than the number required for the corresponding operator, as
10605 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010606 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010607 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010608 if (Op != OO_Call &&
10609 ((NumParams == 1 && !CanBeUnaryOperator) ||
10610 (NumParams == 2 && !CanBeBinaryOperator) ||
10611 (NumParams < 1) || (NumParams > 2))) {
10612 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010613 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010614 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010615 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010616 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010617 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010618 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010619 assert(CanBeBinaryOperator &&
10620 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010621 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010622 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010623
Chris Lattner416e46f2008-11-21 07:57:12 +000010624 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010625 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010626 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010627
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010628 // Overloaded operators other than operator() cannot be variadic.
10629 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010630 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010631 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010632 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010633 }
10634
10635 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010636 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10637 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010638 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010639 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010640 }
10641
10642 // C++ [over.inc]p1:
10643 // The user-defined function called operator++ implements the
10644 // prefix and postfix ++ operator. If this function is a member
10645 // function with no parameters, or a non-member function with one
10646 // parameter of class or enumeration type, it defines the prefix
10647 // increment operator ++ for objects of that type. If the function
10648 // is a member function with one parameter (which shall be of type
10649 // int) or a non-member function with two parameters (the second
10650 // of which shall be of type int), it defines the postfix
10651 // increment operator ++ for objects of that type.
10652 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10653 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10654 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010655 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010656 ParamIsInt = BT->getKind() == BuiltinType::Int;
10657
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010658 if (!ParamIsInt)
10659 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010660 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010661 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010662 }
10663
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010664 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010665}
Chris Lattner5a003a42008-12-17 07:09:26 +000010666
Sean Hunta6c058d2010-01-13 09:01:02 +000010667/// CheckLiteralOperatorDeclaration - Check whether the declaration
10668/// of this literal operator function is well-formed. If so, returns
10669/// false; otherwise, emits appropriate diagnostics and returns true.
10670bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010671 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010672 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10673 << FnDecl->getDeclName();
10674 return true;
10675 }
10676
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010677 if (FnDecl->isExternC()) {
10678 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10679 return true;
10680 }
10681
Sean Hunta6c058d2010-01-13 09:01:02 +000010682 bool Valid = false;
10683
Richard Smith36f5cfe2012-03-09 08:00:36 +000010684 // This might be the definition of a literal operator template.
10685 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10686 // This might be a specialization of a literal operator template.
10687 if (!TpDecl)
10688 TpDecl = FnDecl->getPrimaryTemplate();
10689
Sean Hunt216c2782010-04-07 23:11:06 +000010690 // template <char...> type operator "" name() is the only valid template
10691 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010692 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010693 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010694 // Must have only one template parameter
10695 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10696 if (Params->size() == 1) {
10697 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010698 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010699
Sean Hunt216c2782010-04-07 23:11:06 +000010700 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010701 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10702 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10703 Valid = true;
10704 }
10705 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010706 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010707 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010708 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10709
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010710 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010711
Sean Hunt30019c02010-04-07 22:57:35 +000010712 // unsigned long long int, long double, and any character type are allowed
10713 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010714 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10715 Context.hasSameType(T, Context.LongDoubleTy) ||
10716 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010717 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010718 Context.hasSameType(T, Context.Char16Ty) ||
10719 Context.hasSameType(T, Context.Char32Ty)) {
10720 if (++Param == FnDecl->param_end())
10721 Valid = true;
10722 goto FinishedParams;
10723 }
10724
Sean Hunt30019c02010-04-07 22:57:35 +000010725 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010726 const PointerType *PT = T->getAs<PointerType>();
10727 if (!PT)
10728 goto FinishedParams;
10729 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010730 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010731 goto FinishedParams;
10732 T = T.getUnqualifiedType();
10733
10734 // Move on to the second parameter;
10735 ++Param;
10736
10737 // If there is no second parameter, the first must be a const char *
10738 if (Param == FnDecl->param_end()) {
10739 if (Context.hasSameType(T, Context.CharTy))
10740 Valid = true;
10741 goto FinishedParams;
10742 }
10743
10744 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10745 // are allowed as the first parameter to a two-parameter function
10746 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010747 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010748 Context.hasSameType(T, Context.Char16Ty) ||
10749 Context.hasSameType(T, Context.Char32Ty)))
10750 goto FinishedParams;
10751
10752 // The second and final parameter must be an std::size_t
10753 T = (*Param)->getType().getUnqualifiedType();
10754 if (Context.hasSameType(T, Context.getSizeType()) &&
10755 ++Param == FnDecl->param_end())
10756 Valid = true;
10757 }
10758
10759 // FIXME: This diagnostic is absolutely terrible.
10760FinishedParams:
10761 if (!Valid) {
10762 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10763 << FnDecl->getDeclName();
10764 return true;
10765 }
10766
Richard Smitha9e88b22012-03-09 08:16:22 +000010767 // A parameter-declaration-clause containing a default argument is not
10768 // equivalent to any of the permitted forms.
10769 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10770 ParamEnd = FnDecl->param_end();
10771 Param != ParamEnd; ++Param) {
10772 if ((*Param)->hasDefaultArg()) {
10773 Diag((*Param)->getDefaultArgRange().getBegin(),
10774 diag::err_literal_operator_default_argument)
10775 << (*Param)->getDefaultArgRange();
10776 break;
10777 }
10778 }
10779
Richard Smith2fb4ae32012-03-08 02:39:21 +000010780 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010781 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10782 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010783 // C++11 [usrlit.suffix]p1:
10784 // Literal suffix identifiers that do not start with an underscore
10785 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010786 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10787 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010788 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010789
Sean Hunta6c058d2010-01-13 09:01:02 +000010790 return false;
10791}
10792
Douglas Gregor074149e2009-01-05 19:45:36 +000010793/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10794/// linkage specification, including the language and (if present)
10795/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10796/// the location of the language string literal, which is provided
10797/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10798/// the '{' brace. Otherwise, this linkage specification does not
10799/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010800Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10801 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010802 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010803 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010804 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010805 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010806 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010807 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010808 Language = LinkageSpecDecl::lang_cxx;
10809 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010810 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010811 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010812 }
Mike Stump1eb44332009-09-09 15:08:12 +000010813
Chris Lattnercc98eac2008-12-17 07:13:27 +000010814 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010815
Douglas Gregor074149e2009-01-05 19:45:36 +000010816 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010817 ExternLoc, LangLoc, Language,
10818 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010819 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010820 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010821 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010822}
10823
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010824/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010825/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10826/// valid, it's the position of the closing '}' brace in a linkage
10827/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010828Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010829 Decl *LinkageSpec,
10830 SourceLocation RBraceLoc) {
10831 if (LinkageSpec) {
10832 if (RBraceLoc.isValid()) {
10833 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10834 LSDecl->setRBraceLoc(RBraceLoc);
10835 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010836 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010837 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010838 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010839}
10840
Michael Han684aa732013-02-22 17:15:32 +000010841Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10842 AttributeList *AttrList,
10843 SourceLocation SemiLoc) {
10844 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10845 // Attribute declarations appertain to empty declaration so we handle
10846 // them here.
10847 if (AttrList)
10848 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010849
Michael Han684aa732013-02-22 17:15:32 +000010850 CurContext->addDecl(ED);
10851 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010852}
10853
Douglas Gregord308e622009-05-18 20:51:54 +000010854/// \brief Perform semantic analysis for the variable declaration that
10855/// occurs within a C++ catch clause, returning the newly-created
10856/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010857VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010858 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010859 SourceLocation StartLoc,
10860 SourceLocation Loc,
10861 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010862 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010863 QualType ExDeclType = TInfo->getType();
10864
Sebastian Redl4b07b292008-12-22 19:15:10 +000010865 // Arrays and functions decay.
10866 if (ExDeclType->isArrayType())
10867 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10868 else if (ExDeclType->isFunctionType())
10869 ExDeclType = Context.getPointerType(ExDeclType);
10870
10871 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10872 // The exception-declaration shall not denote a pointer or reference to an
10873 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010874 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010875 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010876 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010877 Invalid = true;
10878 }
Douglas Gregord308e622009-05-18 20:51:54 +000010879
Sebastian Redl4b07b292008-12-22 19:15:10 +000010880 QualType BaseType = ExDeclType;
10881 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010882 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010883 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010884 BaseType = Ptr->getPointeeType();
10885 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010886 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010887 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010888 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010889 BaseType = Ref->getPointeeType();
10890 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010891 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010892 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010893 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010894 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010895 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010896
Mike Stump1eb44332009-09-09 15:08:12 +000010897 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010898 RequireNonAbstractType(Loc, ExDeclType,
10899 diag::err_abstract_type_in_decl,
10900 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010901 Invalid = true;
10902
John McCall5a180392010-07-24 00:37:23 +000010903 // Only the non-fragile NeXT runtime currently supports C++ catches
10904 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010905 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010906 QualType T = ExDeclType;
10907 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10908 T = RT->getPointeeType();
10909
10910 if (T->isObjCObjectType()) {
10911 Diag(Loc, diag::err_objc_object_catch);
10912 Invalid = true;
10913 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010914 // FIXME: should this be a test for macosx-fragile specifically?
10915 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010916 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010917 }
10918 }
10919
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010920 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010921 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010922 ExDecl->setExceptionVariable(true);
10923
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010924 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010925 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010926 Invalid = true;
10927
Douglas Gregorc41b8782011-07-06 18:14:43 +000010928 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010929 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010930 // Insulate this from anything else we might currently be parsing.
10931 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10932
Douglas Gregor6d182892010-03-05 23:38:39 +000010933 // C++ [except.handle]p16:
10934 // The object declared in an exception-declaration or, if the
10935 // exception-declaration does not specify a name, a temporary (12.2) is
10936 // copy-initialized (8.5) from the exception object. [...]
10937 // The object is destroyed when the handler exits, after the destruction
10938 // of any automatic objects initialized within the handler.
10939 //
10940 // We just pretend to initialize the object with itself, then make sure
10941 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010942 QualType initType = ExDeclType;
10943
10944 InitializedEntity entity =
10945 InitializedEntity::InitializeVariable(ExDecl);
10946 InitializationKind initKind =
10947 InitializationKind::CreateCopy(Loc, SourceLocation());
10948
10949 Expr *opaqueValue =
10950 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010951 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10952 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010953 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010954 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010955 else {
10956 // If the constructor used was non-trivial, set this as the
10957 // "initializer".
10958 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10959 if (!construct->getConstructor()->isTrivial()) {
10960 Expr *init = MaybeCreateExprWithCleanups(construct);
10961 ExDecl->setInit(init);
10962 }
10963
10964 // And make sure it's destructable.
10965 FinalizeVarWithDestructor(ExDecl, recordType);
10966 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010967 }
10968 }
10969
Douglas Gregord308e622009-05-18 20:51:54 +000010970 if (Invalid)
10971 ExDecl->setInvalidDecl();
10972
10973 return ExDecl;
10974}
10975
10976/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10977/// handler.
John McCalld226f652010-08-21 09:40:31 +000010978Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010979 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010980 bool Invalid = D.isInvalidType();
10981
10982 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010983 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10984 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010985 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10986 D.getIdentifierLoc());
10987 Invalid = true;
10988 }
10989
Sebastian Redl4b07b292008-12-22 19:15:10 +000010990 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010991 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010992 LookupOrdinaryName,
10993 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010994 // The scope should be freshly made just for us. There is just no way
10995 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010996 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010997 if (PrevDecl->isTemplateParameter()) {
10998 // Maybe we will complain about the shadowed template parameter.
10999 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011000 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011001 }
11002 }
11003
Chris Lattnereaaebc72009-04-25 08:06:05 +000011004 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011005 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11006 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011007 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011008 }
11009
Douglas Gregor83cb9422010-09-09 17:09:21 +000011010 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011011 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011012 D.getIdentifierLoc(),
11013 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011014 if (Invalid)
11015 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011016
Sebastian Redl4b07b292008-12-22 19:15:10 +000011017 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011018 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011019 PushOnScopeChains(ExDecl, S);
11020 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011021 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011022
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011023 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011024 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011025}
Anders Carlssonfb311762009-03-14 00:25:26 +000011026
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011027Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011028 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011029 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011030 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011031 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011032
Richard Smithe3f470a2012-07-11 22:37:56 +000011033 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11034 return 0;
11035
11036 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11037 AssertMessage, RParenLoc, false);
11038}
11039
11040Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11041 Expr *AssertExpr,
11042 StringLiteral *AssertMessage,
11043 SourceLocation RParenLoc,
11044 bool Failed) {
11045 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11046 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011047 // In a static_assert-declaration, the constant-expression shall be a
11048 // constant expression that can be contextually converted to bool.
11049 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11050 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011051 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011052
Richard Smithdaaefc52011-12-14 23:32:26 +000011053 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011054 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011055 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011056 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011057 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011058
Richard Smithe3f470a2012-07-11 22:37:56 +000011059 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011060 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011061 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011062 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011063 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011064 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011065 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011066 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011067 }
Mike Stump1eb44332009-09-09 15:08:12 +000011068
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011069 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011070 AssertExpr, AssertMessage, RParenLoc,
11071 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011072
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011073 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011074 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011075}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011076
Douglas Gregor1d869352010-04-07 16:53:43 +000011077/// \brief Perform semantic analysis of the given friend type declaration.
11078///
11079/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011080FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011081 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011082 TypeSourceInfo *TSInfo) {
11083 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11084
11085 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011086 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011087
Richard Smith6b130222011-10-18 21:39:00 +000011088 // C++03 [class.friend]p2:
11089 // An elaborated-type-specifier shall be used in a friend declaration
11090 // for a class.*
11091 //
11092 // * The class-key of the elaborated-type-specifier is required.
11093 if (!ActiveTemplateInstantiations.empty()) {
11094 // Do not complain about the form of friend template types during
11095 // template instantiation; we will already have complained when the
11096 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011097 } else {
11098 if (!T->isElaboratedTypeSpecifier()) {
11099 // If we evaluated the type to a record type, suggest putting
11100 // a tag in front.
11101 if (const RecordType *RT = T->getAs<RecordType>()) {
11102 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011103
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011104 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011105
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011106 Diag(TypeRange.getBegin(),
11107 getLangOpts().CPlusPlus11 ?
11108 diag::warn_cxx98_compat_unelaborated_friend_type :
11109 diag::ext_unelaborated_friend_type)
11110 << (unsigned) RD->getTagKind()
11111 << T
11112 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11113 InsertionText);
11114 } else {
11115 Diag(FriendLoc,
11116 getLangOpts().CPlusPlus11 ?
11117 diag::warn_cxx98_compat_nonclass_type_friend :
11118 diag::ext_nonclass_type_friend)
11119 << T
11120 << TypeRange;
11121 }
11122 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011123 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011124 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011125 diag::warn_cxx98_compat_enum_friend :
11126 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011127 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011128 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011129 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011130
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011131 // C++11 [class.friend]p3:
11132 // A friend declaration that does not declare a function shall have one
11133 // of the following forms:
11134 // friend elaborated-type-specifier ;
11135 // friend simple-type-specifier ;
11136 // friend typename-specifier ;
11137 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11138 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11139 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011140
Douglas Gregor06245bf2010-04-07 17:57:12 +000011141 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011142 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011143 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011144 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011145}
11146
John McCall9a34edb2010-10-19 01:40:49 +000011147/// Handle a friend tag declaration where the scope specifier was
11148/// templated.
11149Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11150 unsigned TagSpec, SourceLocation TagLoc,
11151 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011152 IdentifierInfo *Name,
11153 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011154 AttributeList *Attr,
11155 MultiTemplateParamsArg TempParamLists) {
11156 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11157
11158 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011159 bool Invalid = false;
11160
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011161 if (TemplateParameterList *TemplateParams =
11162 MatchTemplateParametersToScopeSpecifier(
11163 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11164 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011165 if (TemplateParams->size() > 0) {
11166 // This is a declaration of a class template.
11167 if (Invalid)
11168 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011169
Eric Christopher4110e132011-07-21 05:34:24 +000011170 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11171 SS, Name, NameLoc, Attr,
11172 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011173 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011174 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011175 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011176 } else {
11177 // The "template<>" header is extraneous.
11178 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11179 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11180 isExplicitSpecialization = true;
11181 }
11182 }
11183
11184 if (Invalid) return 0;
11185
John McCall9a34edb2010-10-19 01:40:49 +000011186 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011187 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011188 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011189 isAllExplicitSpecializations = false;
11190 break;
11191 }
11192 }
11193
11194 // FIXME: don't ignore attributes.
11195
11196 // If it's explicit specializations all the way down, just forget
11197 // about the template header and build an appropriate non-templated
11198 // friend. TODO: for source fidelity, remember the headers.
11199 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011200 if (SS.isEmpty()) {
11201 bool Owned = false;
11202 bool IsDependent = false;
11203 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11204 Attr, AS_public,
11205 /*ModulePrivateLoc=*/SourceLocation(),
11206 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011207 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011208 /*ScopedEnumUsesClassTag=*/false,
11209 /*UnderlyingType=*/TypeResult());
11210 }
11211
Douglas Gregor2494dd02011-03-01 01:34:45 +000011212 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011213 ElaboratedTypeKeyword Keyword
11214 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011215 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011216 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011217 if (T.isNull())
11218 return 0;
11219
11220 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11221 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011222 DependentNameTypeLoc TL =
11223 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011224 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011225 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011226 TL.setNameLoc(NameLoc);
11227 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011228 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011229 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011230 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011231 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011232 }
11233
11234 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011235 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011236 Friend->setAccess(AS_public);
11237 CurContext->addDecl(Friend);
11238 return Friend;
11239 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011240
11241 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11242
11243
John McCall9a34edb2010-10-19 01:40:49 +000011244
11245 // Handle the case of a templated-scope friend class. e.g.
11246 // template <class T> class A<T>::B;
11247 // FIXME: we don't support these right now.
11248 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11249 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11250 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011251 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011252 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011253 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011254 TL.setNameLoc(NameLoc);
11255
11256 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011257 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011258 Friend->setAccess(AS_public);
11259 Friend->setUnsupportedFriend(true);
11260 CurContext->addDecl(Friend);
11261 return Friend;
11262}
11263
11264
John McCalldd4a3b02009-09-16 22:47:08 +000011265/// Handle a friend type declaration. This works in tandem with
11266/// ActOnTag.
11267///
11268/// Notes on friend class templates:
11269///
11270/// We generally treat friend class declarations as if they were
11271/// declaring a class. So, for example, the elaborated type specifier
11272/// in a friend declaration is required to obey the restrictions of a
11273/// class-head (i.e. no typedefs in the scope chain), template
11274/// parameters are required to match up with simple template-ids, &c.
11275/// However, unlike when declaring a template specialization, it's
11276/// okay to refer to a template specialization without an empty
11277/// template parameter declaration, e.g.
11278/// friend class A<T>::B<unsigned>;
11279/// We permit this as a special case; if there are any template
11280/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011281/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011282Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011283 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011284 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011285
11286 assert(DS.isFriendSpecified());
11287 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11288
John McCalldd4a3b02009-09-16 22:47:08 +000011289 // Try to convert the decl specifier to a type. This works for
11290 // friend templates because ActOnTag never produces a ClassTemplateDecl
11291 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011292 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011293 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11294 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011295 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011296 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011297
Douglas Gregor6ccab972010-12-16 01:14:37 +000011298 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11299 return 0;
11300
John McCalldd4a3b02009-09-16 22:47:08 +000011301 // This is definitely an error in C++98. It's probably meant to
11302 // be forbidden in C++0x, too, but the specification is just
11303 // poorly written.
11304 //
11305 // The problem is with declarations like the following:
11306 // template <T> friend A<T>::foo;
11307 // where deciding whether a class C is a friend or not now hinges
11308 // on whether there exists an instantiation of A that causes
11309 // 'foo' to equal C. There are restrictions on class-heads
11310 // (which we declare (by fiat) elaborated friend declarations to
11311 // be) that makes this tractable.
11312 //
11313 // FIXME: handle "template <> friend class A<T>;", which
11314 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011315 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011316 Diag(Loc, diag::err_tagless_friend_type_template)
11317 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011318 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011319 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011320
John McCall02cace72009-08-28 07:59:38 +000011321 // C++98 [class.friend]p1: A friend of a class is a function
11322 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011323 // This is fixed in DR77, which just barely didn't make the C++03
11324 // deadline. It's also a very silly restriction that seriously
11325 // affects inner classes and which nobody else seems to implement;
11326 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011327 //
11328 // But note that we could warn about it: it's always useless to
11329 // friend one of your own members (it's not, however, worthless to
11330 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011331
John McCalldd4a3b02009-09-16 22:47:08 +000011332 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011333 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011334 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011335 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011336 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011337 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011338 DS.getFriendSpecLoc());
11339 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011340 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011341
11342 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011343 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011344
John McCalldd4a3b02009-09-16 22:47:08 +000011345 D->setAccess(AS_public);
11346 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011347
John McCalld226f652010-08-21 09:40:31 +000011348 return D;
John McCall02cace72009-08-28 07:59:38 +000011349}
11350
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011351NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11352 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011353 const DeclSpec &DS = D.getDeclSpec();
11354
11355 assert(DS.isFriendSpecified());
11356 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11357
11358 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011359 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011360
11361 // C++ [class.friend]p1
11362 // A friend of a class is a function or class....
11363 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011364 // It *doesn't* see through dependent types, which is correct
11365 // according to [temp.arg.type]p3:
11366 // If a declaration acquires a function type through a
11367 // type dependent on a template-parameter and this causes
11368 // a declaration that does not use the syntactic form of a
11369 // function declarator to have a function type, the program
11370 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011371 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011372 Diag(Loc, diag::err_unexpected_friend);
11373
11374 // It might be worthwhile to try to recover by creating an
11375 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011376 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011377 }
11378
11379 // C++ [namespace.memdef]p3
11380 // - If a friend declaration in a non-local class first declares a
11381 // class or function, the friend class or function is a member
11382 // of the innermost enclosing namespace.
11383 // - The name of the friend is not found by simple name lookup
11384 // until a matching declaration is provided in that namespace
11385 // scope (either before or after the class declaration granting
11386 // friendship).
11387 // - If a friend function is called, its name may be found by the
11388 // name lookup that considers functions from namespaces and
11389 // classes associated with the types of the function arguments.
11390 // - When looking for a prior declaration of a class or a function
11391 // declared as a friend, scopes outside the innermost enclosing
11392 // namespace scope are not considered.
11393
John McCall337ec3d2010-10-12 23:13:28 +000011394 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011395 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11396 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011397 assert(Name);
11398
Douglas Gregor6ccab972010-12-16 01:14:37 +000011399 // Check for unexpanded parameter packs.
11400 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11401 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11402 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11403 return 0;
11404
John McCall67d1a672009-08-06 02:15:43 +000011405 // The context we found the declaration in, or in which we should
11406 // create the declaration.
11407 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011408 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011409 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011410 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011411
Richard Smith4e9686b2013-08-09 04:35:01 +000011412 // There are five cases here.
11413 // - There's no scope specifier and we're in a local class. Only look
11414 // for functions declared in the immediately-enclosing block scope.
11415 // We recover from invalid scope qualifiers as if they just weren't there.
11416 FunctionDecl *FunctionContainingLocalClass = 0;
11417 if ((SS.isInvalid() || !SS.isSet()) &&
11418 (FunctionContainingLocalClass =
11419 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11420 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011421 // If a friend declaration appears in a local class and the name
11422 // specified is an unqualified name, a prior declaration is
11423 // looked up without considering scopes that are outside the
11424 // innermost enclosing non-class scope. For a friend function
11425 // declaration, if there is no prior declaration, the program is
11426 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011427
11428 // Find the innermost enclosing non-class scope. This is the block
11429 // scope containing the local class definition (or for a nested class,
11430 // the outer local class).
11431 DCScope = S->getFnParent();
11432
11433 // Look up the function name in the scope.
11434 Previous.clear(LookupLocalFriendName);
11435 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11436
11437 if (!Previous.empty()) {
11438 // All possible previous declarations must have the same context:
11439 // either they were declared at block scope or they are members of
11440 // one of the enclosing local classes.
11441 DC = Previous.getRepresentativeDecl()->getDeclContext();
11442 } else {
11443 // This is ill-formed, but provide the context that we would have
11444 // declared the function in, if we were permitted to, for error recovery.
11445 DC = FunctionContainingLocalClass;
11446 }
11447
11448 // C++ [class.friend]p6:
11449 // A function can be defined in a friend declaration of a class if and
11450 // only if the class is a non-local class (9.8), the function name is
11451 // unqualified, and the function has namespace scope.
11452 if (D.isFunctionDefinition()) {
11453 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11454 }
11455
11456 // - There's no scope specifier, in which case we just go to the
11457 // appropriate scope and look for a function or function template
11458 // there as appropriate.
11459 } else if (SS.isInvalid() || !SS.isSet()) {
11460 // C++11 [namespace.memdef]p3:
11461 // If the name in a friend declaration is neither qualified nor
11462 // a template-id and the declaration is a function or an
11463 // elaborated-type-specifier, the lookup to determine whether
11464 // the entity has been previously declared shall not consider
11465 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011466 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011467
John McCall29ae6e52010-10-13 05:45:15 +000011468 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011469 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011470
Rafael Espindola11dc6342013-04-25 20:12:36 +000011471 // Skip class contexts. If someone can cite chapter and verse
11472 // for this behavior, that would be nice --- it's what GCC and
11473 // EDG do, and it seems like a reasonable intent, but the spec
11474 // really only says that checks for unqualified existing
11475 // declarations should stop at the nearest enclosing namespace,
11476 // not that they should only consider the nearest enclosing
11477 // namespace.
11478 while (DC->isRecord())
11479 DC = DC->getParent();
11480
11481 DeclContext *LookupDC = DC;
11482 while (LookupDC->isTransparentContext())
11483 LookupDC = LookupDC->getParent();
11484
11485 while (true) {
11486 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011487
Rafael Espindola11dc6342013-04-25 20:12:36 +000011488 if (!Previous.empty()) {
11489 DC = LookupDC;
11490 break;
John McCall8a407372010-10-14 22:22:28 +000011491 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011492
11493 if (isTemplateId) {
11494 if (isa<TranslationUnitDecl>(LookupDC)) break;
11495 } else {
11496 if (LookupDC->isFileContext()) break;
11497 }
11498 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011499 }
11500
John McCall380aaa42010-10-13 06:22:15 +000011501 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011502
John McCall337ec3d2010-10-12 23:13:28 +000011503 // - There's a non-dependent scope specifier, in which case we
11504 // compute it and do a previous lookup there for a function
11505 // or function template.
11506 } else if (!SS.getScopeRep()->isDependent()) {
11507 DC = computeDeclContext(SS);
11508 if (!DC) return 0;
11509
11510 if (RequireCompleteDeclContext(SS, DC)) return 0;
11511
11512 LookupQualifiedName(Previous, DC);
11513
11514 // Ignore things found implicitly in the wrong scope.
11515 // TODO: better diagnostics for this case. Suggesting the right
11516 // qualified scope would be nice...
11517 LookupResult::Filter F = Previous.makeFilter();
11518 while (F.hasNext()) {
11519 NamedDecl *D = F.next();
11520 if (!DC->InEnclosingNamespaceSetOf(
11521 D->getDeclContext()->getRedeclContext()))
11522 F.erase();
11523 }
11524 F.done();
11525
11526 if (Previous.empty()) {
11527 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011528 Diag(Loc, diag::err_qualified_friend_not_found)
11529 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011530 return 0;
11531 }
11532
11533 // C++ [class.friend]p1: A friend of a class is a function or
11534 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011535 if (DC->Equals(CurContext))
11536 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011537 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011538 diag::warn_cxx98_compat_friend_is_member :
11539 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011540
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011541 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011542 // C++ [class.friend]p6:
11543 // A function can be defined in a friend declaration of a class if and
11544 // only if the class is a non-local class (9.8), the function name is
11545 // unqualified, and the function has namespace scope.
11546 SemaDiagnosticBuilder DB
11547 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11548
11549 DB << SS.getScopeRep();
11550 if (DC->isFileContext())
11551 DB << FixItHint::CreateRemoval(SS.getRange());
11552 SS.clear();
11553 }
John McCall337ec3d2010-10-12 23:13:28 +000011554
11555 // - There's a scope specifier that does not match any template
11556 // parameter lists, in which case we use some arbitrary context,
11557 // create a method or method template, and wait for instantiation.
11558 // - There's a scope specifier that does match some template
11559 // parameter lists, which we don't handle right now.
11560 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011561 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011562 // C++ [class.friend]p6:
11563 // A function can be defined in a friend declaration of a class if and
11564 // only if the class is a non-local class (9.8), the function name is
11565 // unqualified, and the function has namespace scope.
11566 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11567 << SS.getScopeRep();
11568 }
11569
John McCall337ec3d2010-10-12 23:13:28 +000011570 DC = CurContext;
11571 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011572 }
Douglas Gregor883af832011-10-10 01:11:59 +000011573
John McCall29ae6e52010-10-13 05:45:15 +000011574 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011575 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011576 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11577 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11578 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011579 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011580 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11581 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011582 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011583 }
John McCall67d1a672009-08-06 02:15:43 +000011584 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011585
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011586 // FIXME: This is an egregious hack to cope with cases where the scope stack
11587 // does not contain the declaration context, i.e., in an out-of-line
11588 // definition of a class.
11589 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11590 if (!DCScope) {
11591 FakeDCScope.setEntity(DC);
11592 DCScope = &FakeDCScope;
11593 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011594
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011595 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011596 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011597 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011598 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011599
Douglas Gregor182ddf02009-09-28 00:08:27 +000011600 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011601
Richard Smith4e9686b2013-08-09 04:35:01 +000011602 // If we performed typo correction, we might have added a scope specifier
11603 // and changed the decl context.
11604 DC = ND->getDeclContext();
11605
John McCallab88d972009-08-31 22:39:49 +000011606 // Add the function declaration to the appropriate lookup tables,
11607 // adjusting the redeclarations list as necessary. We don't
11608 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011609 //
John McCallab88d972009-08-31 22:39:49 +000011610 // Also update the scope-based lookup if the target context's
11611 // lookup context is in lexical scope.
11612 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011613 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011614 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011615 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011616 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011617 }
John McCall02cace72009-08-28 07:59:38 +000011618
11619 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011620 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011621 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011622 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011623 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011624
John McCall1f2e1a92012-08-10 03:15:35 +000011625 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011626 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011627 } else {
11628 if (DC->isRecord()) CheckFriendAccess(ND);
11629
John McCall6102ca12010-10-16 06:59:13 +000011630 FunctionDecl *FD;
11631 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11632 FD = FTD->getTemplatedDecl();
11633 else
11634 FD = cast<FunctionDecl>(ND);
11635
David Majnemerf6a144f2013-06-25 23:09:30 +000011636 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11637 // default argument expression, that declaration shall be a definition
11638 // and shall be the only declaration of the function or function
11639 // template in the translation unit.
11640 if (functionDeclHasDefaultArgument(FD)) {
11641 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11642 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11643 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11644 } else if (!D.isFunctionDefinition())
11645 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11646 }
11647
John McCall6102ca12010-10-16 06:59:13 +000011648 // Mark templated-scope function declarations as unsupported.
11649 if (FD->getNumTemplateParameterLists())
11650 FrD->setUnsupportedFriend(true);
11651 }
John McCall337ec3d2010-10-12 23:13:28 +000011652
John McCalld226f652010-08-21 09:40:31 +000011653 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011654}
11655
John McCalld226f652010-08-21 09:40:31 +000011656void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11657 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011658
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011659 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011660 if (!Fn) {
11661 Diag(DelLoc, diag::err_deleted_non_function);
11662 return;
11663 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011664
Douglas Gregoref96ee02012-01-14 16:38:05 +000011665 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011666 // Don't consider the implicit declaration we generate for explicit
11667 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011668 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11669 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011670 Diag(DelLoc, diag::err_deleted_decl_not_first);
11671 Diag(Prev->getLocation(), diag::note_previous_declaration);
11672 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011673 // If the declaration wasn't the first, we delete the function anyway for
11674 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011675 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011676 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011677
11678 if (Fn->isDeleted())
11679 return;
11680
11681 // See if we're deleting a function which is already known to override a
11682 // non-deleted virtual function.
11683 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11684 bool IssuedDiagnostic = false;
11685 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11686 E = MD->end_overridden_methods();
11687 I != E; ++I) {
11688 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11689 if (!IssuedDiagnostic) {
11690 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11691 IssuedDiagnostic = true;
11692 }
11693 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11694 }
11695 }
11696 }
11697
Sean Hunt10620eb2011-05-06 20:44:56 +000011698 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011699}
Sebastian Redl13e88542009-04-27 21:33:24 +000011700
Sean Hunte4246a62011-05-12 06:15:49 +000011701void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011702 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011703
11704 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011705 if (MD->getParent()->isDependentType()) {
11706 MD->setDefaulted();
11707 MD->setExplicitlyDefaulted();
11708 return;
11709 }
11710
Sean Hunte4246a62011-05-12 06:15:49 +000011711 CXXSpecialMember Member = getSpecialMember(MD);
11712 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011713 if (!MD->isInvalidDecl())
11714 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011715 return;
11716 }
11717
11718 MD->setDefaulted();
11719 MD->setExplicitlyDefaulted();
11720
Sean Huntcd10dec2011-05-23 23:14:04 +000011721 // If this definition appears within the record, do the checking when
11722 // the record is complete.
11723 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011724 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011725 // Find the uninstantiated declaration that actually had the '= default'
11726 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011727 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011728
Richard Smith12fef492013-03-27 00:22:47 +000011729 // If the method was defaulted on its first declaration, we will have
11730 // already performed the checking in CheckCompletedCXXClass. Such a
11731 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011732 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011733 return;
11734
Richard Smithb9d0b762012-07-27 04:22:15 +000011735 CheckExplicitlyDefaultedSpecialMember(MD);
11736
Richard Smith1d28caf2012-12-11 01:14:52 +000011737 // The exception specification is needed because we are defining the
11738 // function.
11739 ResolveExceptionSpec(DefaultLoc,
11740 MD->getType()->castAs<FunctionProtoType>());
11741
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011742 if (MD->isInvalidDecl())
11743 return;
11744
Sean Hunte4246a62011-05-12 06:15:49 +000011745 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011746 case CXXDefaultConstructor:
11747 DefineImplicitDefaultConstructor(DefaultLoc,
11748 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011749 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011750 case CXXCopyConstructor:
11751 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011752 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011753 case CXXCopyAssignment:
11754 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011755 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011756 case CXXDestructor:
11757 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011758 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011759 case CXXMoveConstructor:
11760 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011761 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011762 case CXXMoveAssignment:
11763 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011764 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011765 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011766 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011767 }
11768 } else {
11769 Diag(DefaultLoc, diag::err_default_special_members);
11770 }
11771}
11772
Sebastian Redl13e88542009-04-27 21:33:24 +000011773static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011774 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011775 Stmt *SubStmt = *CI;
11776 if (!SubStmt)
11777 continue;
11778 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011779 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011780 diag::err_return_in_constructor_handler);
11781 if (!isa<Expr>(SubStmt))
11782 SearchForReturnInStmt(Self, SubStmt);
11783 }
11784}
11785
11786void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11787 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11788 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11789 SearchForReturnInStmt(*this, Handler);
11790 }
11791}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011792
David Blaikie299adab2013-01-18 23:03:15 +000011793bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011794 const CXXMethodDecl *Old) {
11795 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11796 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11797
11798 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11799
11800 // If the calling conventions match, everything is fine
11801 if (NewCC == OldCC)
11802 return false;
11803
Reid Kleckneref072032013-08-27 23:08:25 +000011804 Diag(New->getLocation(),
11805 diag::err_conflicting_overriding_cc_attributes)
11806 << New->getDeclName() << New->getType() << Old->getType();
11807 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11808 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011809}
11810
Mike Stump1eb44332009-09-09 15:08:12 +000011811bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011812 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011813 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11814 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011815
Chandler Carruth73857792010-02-15 11:53:20 +000011816 if (Context.hasSameType(NewTy, OldTy) ||
11817 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011818 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011819
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011820 // Check if the return types are covariant
11821 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011822
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011823 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011824 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11825 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011826 NewClassTy = NewPT->getPointeeType();
11827 OldClassTy = OldPT->getPointeeType();
11828 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011829 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11830 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11831 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11832 NewClassTy = NewRT->getPointeeType();
11833 OldClassTy = OldRT->getPointeeType();
11834 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011835 }
11836 }
Mike Stump1eb44332009-09-09 15:08:12 +000011837
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011838 // The return types aren't either both pointers or references to a class type.
11839 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011840 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011841 diag::err_different_return_type_for_overriding_virtual_function)
11842 << New->getDeclName() << NewTy << OldTy;
11843 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011844
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011845 return true;
11846 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011847
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011848 // C++ [class.virtual]p6:
11849 // If the return type of D::f differs from the return type of B::f, the
11850 // class type in the return type of D::f shall be complete at the point of
11851 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011852 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11853 if (!RT->isBeingDefined() &&
11854 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011855 diag::err_covariant_return_incomplete,
11856 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011857 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011858 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011859
Douglas Gregora4923eb2009-11-16 21:35:15 +000011860 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011861 // Check if the new class derives from the old class.
11862 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11863 Diag(New->getLocation(),
11864 diag::err_covariant_return_not_derived)
11865 << New->getDeclName() << NewTy << OldTy;
11866 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11867 return true;
11868 }
Mike Stump1eb44332009-09-09 15:08:12 +000011869
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011870 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011871 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011872 diag::err_covariant_return_inaccessible_base,
11873 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11874 // FIXME: Should this point to the return type?
11875 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011876 // FIXME: this note won't trigger for delayed access control
11877 // diagnostics, and it's impossible to get an undelayed error
11878 // here from access control during the original parse because
11879 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011880 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11881 return true;
11882 }
11883 }
Mike Stump1eb44332009-09-09 15:08:12 +000011884
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011885 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011886 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011887 Diag(New->getLocation(),
11888 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011889 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011890 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11891 return true;
11892 };
Mike Stump1eb44332009-09-09 15:08:12 +000011893
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011894
11895 // The new class type must have the same or less qualifiers as the old type.
11896 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11897 Diag(New->getLocation(),
11898 diag::err_covariant_return_type_class_type_more_qualified)
11899 << New->getDeclName() << NewTy << OldTy;
11900 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11901 return true;
11902 };
Mike Stump1eb44332009-09-09 15:08:12 +000011903
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011904 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011905}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011906
Douglas Gregor4ba31362009-12-01 17:24:26 +000011907/// \brief Mark the given method pure.
11908///
11909/// \param Method the method to be marked pure.
11910///
11911/// \param InitRange the source range that covers the "0" initializer.
11912bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011913 SourceLocation EndLoc = InitRange.getEnd();
11914 if (EndLoc.isValid())
11915 Method->setRangeEnd(EndLoc);
11916
Douglas Gregor4ba31362009-12-01 17:24:26 +000011917 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11918 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011919 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011920 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011921
11922 if (!Method->isInvalidDecl())
11923 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11924 << Method->getDeclName() << InitRange;
11925 return true;
11926}
11927
Douglas Gregor552e2992012-02-21 02:22:07 +000011928/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011929static bool isStaticDataMember(const Decl *D) {
11930 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
11931 return Var->isStaticDataMember();
11932
11933 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000011934}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011935
John McCall731ad842009-12-19 09:28:58 +000011936/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11937/// an initializer for the out-of-line declaration 'Dcl'. The scope
11938/// is a fresh scope pushed for just this purpose.
11939///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011940/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11941/// static data member of class X, names should be looked up in the scope of
11942/// class X.
John McCalld226f652010-08-21 09:40:31 +000011943void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011944 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011945 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011946
John McCall731ad842009-12-19 09:28:58 +000011947 // We should only get called for declarations with scope specifiers, like:
11948 // int foo::bar;
11949 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011950 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011951
11952 // If we are parsing the initializer for a static data member, push a
11953 // new expression evaluation context that is associated with this static
11954 // data member.
11955 if (isStaticDataMember(D))
11956 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011957}
11958
11959/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011960/// initializer for the out-of-line declaration 'D'.
11961void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011962 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011963 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011964
Douglas Gregor552e2992012-02-21 02:22:07 +000011965 if (isStaticDataMember(D))
11966 PopExpressionEvaluationContext();
11967
John McCall731ad842009-12-19 09:28:58 +000011968 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011969 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011970}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011971
11972/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11973/// C++ if/switch/while/for statement.
11974/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011975DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011976 // C++ 6.4p2:
11977 // The declarator shall not specify a function or an array.
11978 // The type-specifier-seq shall not contain typedef and shall not declare a
11979 // new class or enumeration.
11980 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11981 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011982
11983 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011984 if (!Dcl)
11985 return true;
11986
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011987 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11988 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011989 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011990 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011991 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011992
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011993 return Dcl;
11994}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011995
Douglas Gregordfe65432011-07-28 19:11:31 +000011996void Sema::LoadExternalVTableUses() {
11997 if (!ExternalSource)
11998 return;
11999
12000 SmallVector<ExternalVTableUse, 4> VTables;
12001 ExternalSource->ReadUsedVTables(VTables);
12002 SmallVector<VTableUse, 4> NewUses;
12003 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12004 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12005 = VTablesUsed.find(VTables[I].Record);
12006 // Even if a definition wasn't required before, it may be required now.
12007 if (Pos != VTablesUsed.end()) {
12008 if (!Pos->second && VTables[I].DefinitionRequired)
12009 Pos->second = true;
12010 continue;
12011 }
12012
12013 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12014 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12015 }
12016
12017 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12018}
12019
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012020void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12021 bool DefinitionRequired) {
12022 // Ignore any vtable uses in unevaluated operands or for classes that do
12023 // not have a vtable.
12024 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012025 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012026 return;
12027
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012028 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012029 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012030 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12031 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12032 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12033 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012034 // If we already had an entry, check to see if we are promoting this vtable
12035 // to required a definition. If so, we need to reappend to the VTableUses
12036 // list, since we may have already processed the first entry.
12037 if (DefinitionRequired && !Pos.first->second) {
12038 Pos.first->second = true;
12039 } else {
12040 // Otherwise, we can early exit.
12041 return;
12042 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012043 }
12044
12045 // Local classes need to have their virtual members marked
12046 // immediately. For all other classes, we mark their virtual members
12047 // at the end of the translation unit.
12048 if (Class->isLocalClass())
12049 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012050 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012051 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012052}
12053
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012054bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012055 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012056 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012057 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012058
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012059 // Note: The VTableUses vector could grow as a result of marking
12060 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012061 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012062 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012063 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012064 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012065 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012066 if (!Class)
12067 continue;
12068
12069 SourceLocation Loc = VTableUses[I].second;
12070
Richard Smithb9d0b762012-07-27 04:22:15 +000012071 bool DefineVTable = true;
12072
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012073 // If this class has a key function, but that key function is
12074 // defined in another translation unit, we don't need to emit the
12075 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012076 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012077 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012078 // The key function is in another translation unit.
12079 DefineVTable = false;
12080 TemplateSpecializationKind TSK =
12081 KeyFunction->getTemplateSpecializationKind();
12082 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12083 TSK != TSK_ImplicitInstantiation &&
12084 "Instantiations don't have key functions");
12085 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012086 } else if (!KeyFunction) {
12087 // If we have a class with no key function that is the subject
12088 // of an explicit instantiation declaration, suppress the
12089 // vtable; it will live with the explicit instantiation
12090 // definition.
12091 bool IsExplicitInstantiationDeclaration
12092 = Class->getTemplateSpecializationKind()
12093 == TSK_ExplicitInstantiationDeclaration;
12094 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12095 REnd = Class->redecls_end();
12096 R != REnd; ++R) {
12097 TemplateSpecializationKind TSK
12098 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12099 if (TSK == TSK_ExplicitInstantiationDeclaration)
12100 IsExplicitInstantiationDeclaration = true;
12101 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12102 IsExplicitInstantiationDeclaration = false;
12103 break;
12104 }
12105 }
12106
12107 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012108 DefineVTable = false;
12109 }
12110
12111 // The exception specifications for all virtual members may be needed even
12112 // if we are not providing an authoritative form of the vtable in this TU.
12113 // We may choose to emit it available_externally anyway.
12114 if (!DefineVTable) {
12115 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12116 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012117 }
12118
12119 // Mark all of the virtual members of this class as referenced, so
12120 // that we can build a vtable. Then, tell the AST consumer that a
12121 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012122 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012123 MarkVirtualMembersReferenced(Loc, Class);
12124 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12125 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12126
12127 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012128 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012129 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012130 const FunctionDecl *KeyFunctionDef = 0;
12131 if (!KeyFunction ||
12132 (KeyFunction->hasBody(KeyFunctionDef) &&
12133 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012134 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12135 TSK_ExplicitInstantiationDefinition
12136 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12137 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012138 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012139 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012140 VTableUses.clear();
12141
Douglas Gregor78844032011-04-22 22:25:37 +000012142 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012143}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012144
Richard Smithb9d0b762012-07-27 04:22:15 +000012145void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12146 const CXXRecordDecl *RD) {
12147 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12148 E = RD->method_end(); I != E; ++I)
12149 if ((*I)->isVirtual() && !(*I)->isPure())
12150 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12151}
12152
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012153void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12154 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012155 // Mark all functions which will appear in RD's vtable as used.
12156 CXXFinalOverriderMap FinalOverriders;
12157 RD->getFinalOverriders(FinalOverriders);
12158 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12159 E = FinalOverriders.end();
12160 I != E; ++I) {
12161 for (OverridingMethods::const_iterator OI = I->second.begin(),
12162 OE = I->second.end();
12163 OI != OE; ++OI) {
12164 assert(OI->second.size() > 0 && "no final overrider");
12165 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012166
Richard Smithff817f72012-07-07 06:59:51 +000012167 // C++ [basic.def.odr]p2:
12168 // [...] A virtual member function is used if it is not pure. [...]
12169 if (!Overrider->isPure())
12170 MarkFunctionReferenced(Loc, Overrider);
12171 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012172 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012173
12174 // Only classes that have virtual bases need a VTT.
12175 if (RD->getNumVBases() == 0)
12176 return;
12177
12178 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12179 e = RD->bases_end(); i != e; ++i) {
12180 const CXXRecordDecl *Base =
12181 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012182 if (Base->getNumVBases() == 0)
12183 continue;
12184 MarkVirtualMembersReferenced(Loc, Base);
12185 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012186}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012187
12188/// SetIvarInitializers - This routine builds initialization ASTs for the
12189/// Objective-C implementation whose ivars need be initialized.
12190void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012191 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012192 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012193 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012194 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012195 CollectIvarsToConstructOrDestruct(OID, ivars);
12196 if (ivars.empty())
12197 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012198 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012199 for (unsigned i = 0; i < ivars.size(); i++) {
12200 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012201 if (Field->isInvalidDecl())
12202 continue;
12203
Sean Huntcbb67482011-01-08 20:30:50 +000012204 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012205 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12206 InitializationKind InitKind =
12207 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012208
12209 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12210 ExprResult MemberInit =
12211 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012212 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012213 // Note, MemberInit could actually come back empty if no initialization
12214 // is required (e.g., because it would call a trivial default constructor)
12215 if (!MemberInit.get() || MemberInit.isInvalid())
12216 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012217
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012218 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012219 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12220 SourceLocation(),
12221 MemberInit.takeAs<Expr>(),
12222 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012223 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012224
12225 // Be sure that the destructor is accessible and is marked as referenced.
12226 if (const RecordType *RecordTy
12227 = Context.getBaseElementType(Field->getType())
12228 ->getAs<RecordType>()) {
12229 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012230 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012231 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012232 CheckDestructorAccess(Field->getLocation(), Destructor,
12233 PDiag(diag::err_access_dtor_ivar)
12234 << Context.getBaseElementType(Field->getType()));
12235 }
12236 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012237 }
12238 ObjCImplementation->setIvarInitializers(Context,
12239 AllToInit.data(), AllToInit.size());
12240 }
12241}
Sean Huntfe57eef2011-05-04 05:57:24 +000012242
Sean Huntebcbe1d2011-05-04 23:29:54 +000012243static
12244void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12245 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12246 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12247 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12248 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012249 if (Ctor->isInvalidDecl())
12250 return;
12251
Richard Smitha8eaf002012-08-23 06:16:52 +000012252 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12253
12254 // Target may not be determinable yet, for instance if this is a dependent
12255 // call in an uninstantiated template.
12256 if (Target) {
12257 const FunctionDecl *FNTarget = 0;
12258 (void)Target->hasBody(FNTarget);
12259 Target = const_cast<CXXConstructorDecl*>(
12260 cast_or_null<CXXConstructorDecl>(FNTarget));
12261 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012262
12263 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12264 // Avoid dereferencing a null pointer here.
12265 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12266
12267 if (!Current.insert(Canonical))
12268 return;
12269
12270 // We know that beyond here, we aren't chaining into a cycle.
12271 if (!Target || !Target->isDelegatingConstructor() ||
12272 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012273 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012274 Current.clear();
12275 // We've hit a cycle.
12276 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12277 Current.count(TCanonical)) {
12278 // If we haven't diagnosed this cycle yet, do so now.
12279 if (!Invalid.count(TCanonical)) {
12280 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012281 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012282 << Ctor;
12283
Richard Smitha8eaf002012-08-23 06:16:52 +000012284 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012285 if (TCanonical != Canonical)
12286 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12287
12288 CXXConstructorDecl *C = Target;
12289 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012290 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012291 (void)C->getTargetConstructor()->hasBody(FNTarget);
12292 assert(FNTarget && "Ctor cycle through bodiless function");
12293
Richard Smitha8eaf002012-08-23 06:16:52 +000012294 C = const_cast<CXXConstructorDecl*>(
12295 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012296 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12297 }
12298 }
12299
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012300 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012301 Current.clear();
12302 } else {
12303 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12304 }
12305}
12306
12307
Sean Huntfe57eef2011-05-04 05:57:24 +000012308void Sema::CheckDelegatingCtorCycles() {
12309 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12310
Douglas Gregor0129b562011-07-27 21:57:17 +000012311 for (DelegatingCtorDeclsType::iterator
12312 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012313 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012314 I != E; ++I)
12315 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012316
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012317 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12318 CE = Invalid.end();
12319 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012320 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012321}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012322
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012323namespace {
12324 /// \brief AST visitor that finds references to the 'this' expression.
12325 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12326 Sema &S;
12327
12328 public:
12329 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12330
12331 bool VisitCXXThisExpr(CXXThisExpr *E) {
12332 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12333 << E->isImplicit();
12334 return false;
12335 }
12336 };
12337}
12338
12339bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12340 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12341 if (!TSInfo)
12342 return false;
12343
12344 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012345 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012346 if (!ProtoTL)
12347 return false;
12348
12349 // C++11 [expr.prim.general]p3:
12350 // [The expression this] shall not appear before the optional
12351 // cv-qualifier-seq and it shall not appear within the declaration of a
12352 // static member function (although its type and value category are defined
12353 // within a static member function as they are within a non-static member
12354 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012355 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012356 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012357 FindCXXThisExpr Finder(*this);
12358
12359 // If the return type came after the cv-qualifier-seq, check it now.
12360 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012361 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012362 return true;
12363
12364 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012365 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12366 return true;
12367
12368 return checkThisInStaticMemberFunctionAttributes(Method);
12369}
12370
12371bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12372 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12373 if (!TSInfo)
12374 return false;
12375
12376 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012377 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012378 if (!ProtoTL)
12379 return false;
12380
David Blaikie39e6ab42013-02-18 22:06:02 +000012381 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012382 FindCXXThisExpr Finder(*this);
12383
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012384 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012385 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012386 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012387 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012388 case EST_DynamicNone:
12389 case EST_MSAny:
12390 case EST_None:
12391 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012392
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012393 case EST_ComputedNoexcept:
12394 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12395 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012396
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012397 case EST_Dynamic:
12398 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012399 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012400 E != EEnd; ++E) {
12401 if (!Finder.TraverseType(*E))
12402 return true;
12403 }
12404 break;
12405 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012406
12407 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012408}
12409
12410bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12411 FindCXXThisExpr Finder(*this);
12412
12413 // Check attributes.
12414 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12415 A != AEnd; ++A) {
12416 // FIXME: This should be emitted by tblgen.
12417 Expr *Arg = 0;
12418 ArrayRef<Expr *> Args;
12419 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12420 Arg = G->getArg();
12421 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12422 Arg = G->getArg();
12423 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12424 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12425 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12426 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12427 else if (ExclusiveLockFunctionAttr *ELF
12428 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12429 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12430 else if (SharedLockFunctionAttr *SLF
12431 = dyn_cast<SharedLockFunctionAttr>(*A))
12432 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12433 else if (ExclusiveTrylockFunctionAttr *ETLF
12434 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12435 Arg = ETLF->getSuccessValue();
12436 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12437 } else if (SharedTrylockFunctionAttr *STLF
12438 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12439 Arg = STLF->getSuccessValue();
12440 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12441 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12442 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12443 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12444 Arg = LR->getArg();
12445 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12446 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12447 else if (ExclusiveLocksRequiredAttr *ELR
12448 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12449 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12450 else if (SharedLocksRequiredAttr *SLR
12451 = dyn_cast<SharedLocksRequiredAttr>(*A))
12452 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12453
12454 if (Arg && !Finder.TraverseStmt(Arg))
12455 return true;
12456
12457 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12458 if (!Finder.TraverseStmt(Args[I]))
12459 return true;
12460 }
12461 }
12462
12463 return false;
12464}
12465
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012466void
12467Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12468 ArrayRef<ParsedType> DynamicExceptions,
12469 ArrayRef<SourceRange> DynamicExceptionRanges,
12470 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012471 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012472 FunctionProtoType::ExtProtoInfo &EPI) {
12473 Exceptions.clear();
12474 EPI.ExceptionSpecType = EST;
12475 if (EST == EST_Dynamic) {
12476 Exceptions.reserve(DynamicExceptions.size());
12477 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12478 // FIXME: Preserve type source info.
12479 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12480
12481 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12482 collectUnexpandedParameterPacks(ET, Unexpanded);
12483 if (!Unexpanded.empty()) {
12484 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12485 UPPC_ExceptionType,
12486 Unexpanded);
12487 continue;
12488 }
12489
12490 // Check that the type is valid for an exception spec, and
12491 // drop it if not.
12492 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12493 Exceptions.push_back(ET);
12494 }
12495 EPI.NumExceptions = Exceptions.size();
12496 EPI.Exceptions = Exceptions.data();
12497 return;
12498 }
12499
12500 if (EST == EST_ComputedNoexcept) {
12501 // If an error occurred, there's no expression here.
12502 if (NoexceptExpr) {
12503 assert((NoexceptExpr->isTypeDependent() ||
12504 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12505 Context.BoolTy) &&
12506 "Parser should have made sure that the expression is boolean");
12507 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12508 EPI.ExceptionSpecType = EST_BasicNoexcept;
12509 return;
12510 }
12511
12512 if (!NoexceptExpr->isValueDependent())
12513 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012514 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012515 /*AllowFold*/ false).take();
12516 EPI.NoexceptExpr = NoexceptExpr;
12517 }
12518 return;
12519 }
12520}
12521
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012522/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12523Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12524 // Implicitly declared functions (e.g. copy constructors) are
12525 // __host__ __device__
12526 if (D->isImplicit())
12527 return CFT_HostDevice;
12528
12529 if (D->hasAttr<CUDAGlobalAttr>())
12530 return CFT_Global;
12531
12532 if (D->hasAttr<CUDADeviceAttr>()) {
12533 if (D->hasAttr<CUDAHostAttr>())
12534 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012535 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012536 }
12537
12538 return CFT_Host;
12539}
12540
12541bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12542 CUDAFunctionTarget CalleeTarget) {
12543 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12544 // Callable from the device only."
12545 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12546 return true;
12547
12548 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12549 // Callable from the host only."
12550 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12551 // Callable from the host only."
12552 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12553 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12554 return true;
12555
12556 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12557 return true;
12558
12559 return false;
12560}
John McCall76da55d2013-04-16 07:28:30 +000012561
12562/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12563///
12564MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12565 SourceLocation DeclStart,
12566 Declarator &D, Expr *BitWidth,
12567 InClassInitStyle InitStyle,
12568 AccessSpecifier AS,
12569 AttributeList *MSPropertyAttr) {
12570 IdentifierInfo *II = D.getIdentifier();
12571 if (!II) {
12572 Diag(DeclStart, diag::err_anonymous_property);
12573 return NULL;
12574 }
12575 SourceLocation Loc = D.getIdentifierLoc();
12576
12577 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12578 QualType T = TInfo->getType();
12579 if (getLangOpts().CPlusPlus) {
12580 CheckExtraCXXDefaultArguments(D);
12581
12582 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12583 UPPC_DataMemberType)) {
12584 D.setInvalidType();
12585 T = Context.IntTy;
12586 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12587 }
12588 }
12589
12590 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12591
12592 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12593 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12594 diag::err_invalid_thread)
12595 << DeclSpec::getSpecifierName(TSCS);
12596
12597 // Check to see if this name was declared as a member previously
12598 NamedDecl *PrevDecl = 0;
12599 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12600 LookupName(Previous, S);
12601 switch (Previous.getResultKind()) {
12602 case LookupResult::Found:
12603 case LookupResult::FoundUnresolvedValue:
12604 PrevDecl = Previous.getAsSingle<NamedDecl>();
12605 break;
12606
12607 case LookupResult::FoundOverloaded:
12608 PrevDecl = Previous.getRepresentativeDecl();
12609 break;
12610
12611 case LookupResult::NotFound:
12612 case LookupResult::NotFoundInCurrentInstantiation:
12613 case LookupResult::Ambiguous:
12614 break;
12615 }
12616
12617 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12618 // Maybe we will complain about the shadowed template parameter.
12619 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12620 // Just pretend that we didn't see the previous declaration.
12621 PrevDecl = 0;
12622 }
12623
12624 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12625 PrevDecl = 0;
12626
12627 SourceLocation TSSL = D.getLocStart();
12628 MSPropertyDecl *NewPD;
12629 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12630 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12631 II, T, TInfo, TSSL,
12632 Data.GetterId, Data.SetterId);
12633 ProcessDeclAttributes(TUScope, NewPD, D);
12634 NewPD->setAccess(AS);
12635
12636 if (NewPD->isInvalidDecl())
12637 Record->setInvalidDecl();
12638
12639 if (D.getDeclSpec().isModulePrivateSpecified())
12640 NewPD->setModulePrivate();
12641
12642 if (NewPD->isInvalidDecl() && PrevDecl) {
12643 // Don't introduce NewFD into scope; there's already something
12644 // with the same name in the same scope.
12645 } else if (II) {
12646 PushOnScopeChains(NewPD, S);
12647 } else
12648 Record->addDecl(NewPD);
12649
12650 return NewPD;
12651}