blob: d4f9cc4380a77b309c11a4490b0ac80dc074f4d4 [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:
Richard Smitha41c97a2013-09-20 01:15:31 +0000441 // 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
Douglas Gregor6cc15182009-09-11 18:44:32 +0000444 // 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;
Richard Smitha41c97a2013-09-20 01:15:31 +0000453
454 // The declaration context corresponding to the scope is the semantic
455 // parent, unless this is a local function declaration, in which case
456 // it is that surrounding function.
457 DeclContext *ScopeDC = New->getLexicalDeclContext();
458 if (!ScopeDC->isFunctionOrMethod())
459 ScopeDC = New->getDeclContext();
460 if (S && !isDeclInScope(ND, ScopeDC, S) &&
461 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000462 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000463 // the same scope and this is not an out-of-line definition of
464 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000465 OldParamHasDfl = false;
466
467 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000468
Francois Pichet8d051e02011-04-10 03:03:52 +0000469 unsigned DiagDefaultParamID =
470 diag::err_param_default_argument_redefinition;
471
472 // MSVC accepts that default parameters be redefined for member functions
473 // of template class. The new default parameter's value is ignored.
474 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000475 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000476 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
477 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000478 // Merge the old default argument into the new parameter.
479 NewParam->setHasInheritedDefaultArg();
480 if (OldParam->hasUninstantiatedDefaultArg())
481 NewParam->setUninstantiatedDefaultArg(
482 OldParam->getUninstantiatedDefaultArg());
483 else
484 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000485 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000486 Invalid = false;
487 }
488 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000489
Francois Pichet8cf90492011-04-10 04:58:30 +0000490 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
491 // hint here. Alternatively, we could walk the type-source information
492 // for NewParam to find the last source location in the type... but it
493 // isn't worth the effort right now. This is the kind of test case that
494 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000495 // int f(int);
496 // void g(int (*fp)(int) = f);
497 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000498 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000499 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000500
501 // Look for the function declaration where the default argument was
502 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000503 for (FunctionDecl *Older = Old->getPreviousDecl();
504 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000505 if (!Older->getParamDecl(p)->hasDefaultArg())
506 break;
507
508 OldParam = Older->getParamDecl(p);
509 }
510
511 Diag(OldParam->getLocation(), diag::note_previous_definition)
512 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000513 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000514 // Merge the old default argument into the new parameter.
515 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000516 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000517 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
John McCall3d6c1782010-05-04 01:53:42 +0000522 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000523 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000524 if (New->getDescribedFunctionTemplate()) {
525 // Paragraph 4, quoted above, only applies to non-template functions.
526 Diag(NewParam->getLocation(),
527 diag::err_param_default_argument_template_redecl)
528 << NewParam->getDefaultArgRange();
529 Diag(Old->getLocation(), diag::note_template_prev_declaration)
530 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000531 } else if (New->getTemplateSpecializationKind()
532 != TSK_ImplicitInstantiation &&
533 New->getTemplateSpecializationKind() != TSK_Undeclared) {
534 // C++ [temp.expr.spec]p21:
535 // Default function arguments shall not be specified in a declaration
536 // or a definition for one of the following explicit specializations:
537 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000538 // - the explicit specialization of a member function template;
539 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000540 // template where the class template specialization to which the
541 // member function specialization belongs is implicitly
542 // instantiated.
543 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
544 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
545 << New->getDeclName()
546 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000547 } else if (New->getDeclContext()->isDependentContext()) {
548 // C++ [dcl.fct.default]p6 (DR217):
549 // Default arguments for a member function of a class template shall
550 // be specified on the initial declaration of the member function
551 // within the class template.
552 //
553 // Reading the tea leaves a bit in DR217 and its reference to DR205
554 // leads me to the conclusion that one cannot add default function
555 // arguments for an out-of-line definition of a member function of a
556 // dependent type.
557 int WhichKind = 2;
558 if (CXXRecordDecl *Record
559 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
560 if (Record->getDescribedClassTemplate())
561 WhichKind = 0;
562 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
563 WhichKind = 1;
564 else
565 WhichKind = 2;
566 }
567
568 Diag(NewParam->getLocation(),
569 diag::err_param_default_argument_member_template_redecl)
570 << WhichKind
571 << NewParam->getDefaultArgRange();
572 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000573 }
574 }
575
Richard Smithb8abff62012-11-28 03:45:24 +0000576 // DR1344: If a default argument is added outside a class definition and that
577 // default argument makes the function a special member function, the program
578 // is ill-formed. This can only happen for constructors.
579 if (isa<CXXConstructorDecl>(New) &&
580 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
581 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
582 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
583 if (NewSM != OldSM) {
584 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
585 assert(NewParam->hasDefaultArg());
586 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
587 << NewParam->getDefaultArgRange() << NewSM;
588 Diag(Old->getLocation(), diag::note_previous_declaration);
589 }
590 }
591
Richard Smithff234882012-02-20 23:28:05 +0000592 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000593 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000594 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000595 if (New->isConstexpr() != Old->isConstexpr()) {
596 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
597 << New << New->isConstexpr();
598 Diag(Old->getLocation(), diag::note_previous_declaration);
599 Invalid = true;
600 }
601
David Majnemerf6a144f2013-06-25 23:09:30 +0000602 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000603 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000604 // the only declaration of the function or function template in the
605 // translation unit.
606 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
607 functionDeclHasDefaultArgument(Old)) {
608 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
609 Diag(Old->getLocation(), diag::note_previous_declaration);
610 Invalid = true;
611 }
612
Douglas Gregore13ad832010-02-12 07:32:17 +0000613 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000614 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000615
Douglas Gregorcda9c672009-02-16 17:45:42 +0000616 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000617}
618
Sebastian Redl60618fa2011-03-12 11:50:43 +0000619/// \brief Merge the exception specifications of two variable declarations.
620///
621/// This is called when there's a redeclaration of a VarDecl. The function
622/// checks if the redeclaration might have an exception specification and
623/// validates compatibility and merges the specs if necessary.
624void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
625 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000626 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000627 return;
628
629 assert(Context.hasSameType(New->getType(), Old->getType()) &&
630 "Should only be called if types are otherwise the same.");
631
632 QualType NewType = New->getType();
633 QualType OldType = Old->getType();
634
635 // We're only interested in pointers and references to functions, as well
636 // as pointers to member functions.
637 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
638 NewType = R->getPointeeType();
639 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
640 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
641 NewType = P->getPointeeType();
642 OldType = OldType->getAs<PointerType>()->getPointeeType();
643 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
644 NewType = M->getPointeeType();
645 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
646 }
647
648 if (!NewType->isFunctionProtoType())
649 return;
650
651 // There's lots of special cases for functions. For function pointers, system
652 // libraries are hopefully not as broken so that we don't need these
653 // workarounds.
654 if (CheckEquivalentExceptionSpec(
655 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
656 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
657 New->setInvalidDecl();
658 }
659}
660
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661/// CheckCXXDefaultArguments - Verify that the default arguments for a
662/// function declaration are well-formed according to C++
663/// [dcl.fct.default].
664void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
665 unsigned NumParams = FD->getNumParams();
666 unsigned p;
667
668 // Find first parameter with a default argument
669 for (p = 0; p < NumParams; ++p) {
670 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000671 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000672 break;
673 }
674
675 // C++ [dcl.fct.default]p4:
676 // In a given function declaration, all parameters
677 // subsequent to a parameter with a default argument shall
678 // have default arguments supplied in this or previous
679 // declarations. A default argument shall not be redefined
680 // by a later declaration (not even to the same value).
681 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000682 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000683 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000684 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000685 if (Param->isInvalidDecl())
686 /* We already complained about this parameter. */;
687 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000688 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000689 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000690 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000691 else
Mike Stump1eb44332009-09-09 15:08:12 +0000692 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000693 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner3d1cee32008-04-08 05:04:30 +0000695 LastMissingDefaultArg = p;
696 }
697 }
698
699 if (LastMissingDefaultArg > 0) {
700 // Some default arguments were missing. Clear out all of the
701 // default arguments up to (and including) the last missing
702 // default argument, so that we leave the function parameters
703 // in a semantically valid state.
704 for (p = 0; p <= LastMissingDefaultArg; ++p) {
705 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000706 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000707 Param->setDefaultArg(0);
708 }
709 }
710 }
711}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000712
Richard Smith9f569cc2011-10-01 02:31:28 +0000713// CheckConstexprParameterTypes - Check whether a function's parameter types
714// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000715// diagnostic and return false.
716static bool CheckConstexprParameterTypes(Sema &SemaRef,
717 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000718 unsigned ArgIndex = 0;
719 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
720 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
721 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
722 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
723 SourceLocation ParamLoc = PD->getLocation();
724 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000726 diag::err_constexpr_non_literal_param,
727 ArgIndex+1, PD->getSourceRange(),
728 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000729 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 }
Joao Matos17d35c32012-08-31 22:18:20 +0000731 return true;
732}
733
734/// \brief Get diagnostic %select index for tag kind for
735/// record diagnostic message.
736/// WARNING: Indexes apply to particular diagnostics only!
737///
738/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000739static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000740 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000741 case TTK_Struct: return 0;
742 case TTK_Interface: return 1;
743 case TTK_Class: return 2;
744 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000745 }
Joao Matos17d35c32012-08-31 22:18:20 +0000746}
747
748// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
749// the requirements of a constexpr function definition or a constexpr
750// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000751// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000752//
Richard Smith86c3ae42012-02-13 03:54:03 +0000753// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
754bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000755 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
756 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000757 // C++11 [dcl.constexpr]p4:
758 // The definition of a constexpr constructor shall satisfy the following
759 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000760 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000761 const CXXRecordDecl *RD = MD->getParent();
762 if (RD->getNumVBases()) {
763 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
764 << isa<CXXConstructorDecl>(NewFD)
765 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
766 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
767 E = RD->vbases_end(); I != E; ++I)
768 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000769 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000770 return false;
771 }
Richard Smith35340502012-01-13 04:54:00 +0000772 }
773
774 if (!isa<CXXConstructorDecl>(NewFD)) {
775 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000776 // The definition of a constexpr function shall satisfy the following
777 // constraints:
778 // - it shall not be virtual;
779 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
780 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000781 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000782
Richard Smith86c3ae42012-02-13 03:54:03 +0000783 // If it's not obvious why this function is virtual, find an overridden
784 // function which uses the 'virtual' keyword.
785 const CXXMethodDecl *WrittenVirtual = Method;
786 while (!WrittenVirtual->isVirtualAsWritten())
787 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
788 if (WrittenVirtual != Method)
789 Diag(WrittenVirtual->getLocation(),
790 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000791 return false;
792 }
793
794 // - its return type shall be a literal type;
795 QualType RT = NewFD->getResultType();
796 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000797 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000798 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000799 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000800 }
801
Richard Smith35340502012-01-13 04:54:00 +0000802 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000803 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000804 return false;
805
Richard Smith9f569cc2011-10-01 02:31:28 +0000806 return true;
807}
808
809/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000810/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000811///
Richard Smitha10b9782013-04-22 15:31:51 +0000812/// \return true if the body is OK (maybe only as an extension), false if we
813/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000814static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000815 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
816 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000817 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
818 // contain only
819 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
820 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
821 switch ((*DclIt)->getKind()) {
822 case Decl::StaticAssert:
823 case Decl::Using:
824 case Decl::UsingShadow:
825 case Decl::UsingDirective:
826 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000827 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000828 // - static_assert-declarations
829 // - using-declarations,
830 // - using-directives,
831 continue;
832
833 case Decl::Typedef:
834 case Decl::TypeAlias: {
835 // - typedef declarations and alias-declarations that do not define
836 // classes or enumerations,
837 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
838 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
839 // Don't allow variably-modified types in constexpr functions.
840 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
841 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
842 << TL.getSourceRange() << TL.getType()
843 << isa<CXXConstructorDecl>(Dcl);
844 return false;
845 }
846 continue;
847 }
848
849 case Decl::Enum:
850 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000851 // C++1y allows types to be defined, not just declared.
852 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
853 SemaRef.Diag(DS->getLocStart(),
854 SemaRef.getLangOpts().CPlusPlus1y
855 ? diag::warn_cxx11_compat_constexpr_type_definition
856 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000857 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000858 continue;
859
Richard Smitha10b9782013-04-22 15:31:51 +0000860 case Decl::EnumConstant:
861 case Decl::IndirectField:
862 case Decl::ParmVar:
863 // These can only appear with other declarations which are banned in
864 // C++11 and permitted in C++1y, so ignore them.
865 continue;
866
867 case Decl::Var: {
868 // C++1y [dcl.constexpr]p3 allows anything except:
869 // a definition of a variable of non-literal type or of static or
870 // thread storage duration or for which no initialization is performed.
871 VarDecl *VD = cast<VarDecl>(*DclIt);
872 if (VD->isThisDeclarationADefinition()) {
873 if (VD->isStaticLocal()) {
874 SemaRef.Diag(VD->getLocation(),
875 diag::err_constexpr_local_var_static)
876 << isa<CXXConstructorDecl>(Dcl)
877 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
878 return false;
879 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000880 if (!VD->getType()->isDependentType() &&
881 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000882 VD->getLocation(), VD->getType(),
883 diag::err_constexpr_local_var_non_literal_type,
884 isa<CXXConstructorDecl>(Dcl)))
885 return false;
886 if (!VD->hasInit()) {
887 SemaRef.Diag(VD->getLocation(),
888 diag::err_constexpr_local_var_no_init)
889 << isa<CXXConstructorDecl>(Dcl);
890 return false;
891 }
892 }
893 SemaRef.Diag(VD->getLocation(),
894 SemaRef.getLangOpts().CPlusPlus1y
895 ? diag::warn_cxx11_compat_constexpr_local_var
896 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000897 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000898 continue;
899 }
900
901 case Decl::NamespaceAlias:
902 case Decl::Function:
903 // These are disallowed in C++11 and permitted in C++1y. Allow them
904 // everywhere as an extension.
905 if (!Cxx1yLoc.isValid())
906 Cxx1yLoc = DS->getLocStart();
907 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000908
909 default:
910 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
911 << isa<CXXConstructorDecl>(Dcl);
912 return false;
913 }
914 }
915
916 return true;
917}
918
919/// Check that the given field is initialized within a constexpr constructor.
920///
921/// \param Dcl The constexpr constructor being checked.
922/// \param Field The field being checked. This may be a member of an anonymous
923/// struct or union nested within the class being checked.
924/// \param Inits All declarations, including anonymous struct/union members and
925/// indirect members, for which any initialization was provided.
926/// \param Diagnosed Set to true if an error is produced.
927static void CheckConstexprCtorInitializer(Sema &SemaRef,
928 const FunctionDecl *Dcl,
929 FieldDecl *Field,
930 llvm::SmallSet<Decl*, 16> &Inits,
931 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000932 if (Field->isInvalidDecl())
933 return;
934
Douglas Gregord61db332011-10-10 17:22:13 +0000935 if (Field->isUnnamedBitfield())
936 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000937
938 if (Field->isAnonymousStructOrUnion() &&
939 Field->getType()->getAsCXXRecordDecl()->isEmpty())
940 return;
941
Richard Smith9f569cc2011-10-01 02:31:28 +0000942 if (!Inits.count(Field)) {
943 if (!Diagnosed) {
944 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
945 Diagnosed = true;
946 }
947 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
948 } else if (Field->isAnonymousStructOrUnion()) {
949 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
950 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
951 I != E; ++I)
952 // If an anonymous union contains an anonymous struct of which any member
953 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000954 if (!RD->isUnion() || Inits.count(*I))
955 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000956 }
957}
958
Richard Smitha10b9782013-04-22 15:31:51 +0000959/// Check the provided statement is allowed in a constexpr function
960/// definition.
961static bool
962CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000963 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000964 SourceLocation &Cxx1yLoc) {
965 // - its function-body shall be [...] a compound-statement that contains only
966 switch (S->getStmtClass()) {
967 case Stmt::NullStmtClass:
968 // - null statements,
969 return true;
970
971 case Stmt::DeclStmtClass:
972 // - static_assert-declarations
973 // - using-declarations,
974 // - using-directives,
975 // - typedef declarations and alias-declarations that do not define
976 // classes or enumerations,
977 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
978 return false;
979 return true;
980
981 case Stmt::ReturnStmtClass:
982 // - and exactly one return statement;
983 if (isa<CXXConstructorDecl>(Dcl)) {
984 // C++1y allows return statements in constexpr constructors.
985 if (!Cxx1yLoc.isValid())
986 Cxx1yLoc = S->getLocStart();
987 return true;
988 }
989
990 ReturnStmts.push_back(S->getLocStart());
991 return true;
992
993 case Stmt::CompoundStmtClass: {
994 // C++1y allows compound-statements.
995 if (!Cxx1yLoc.isValid())
996 Cxx1yLoc = S->getLocStart();
997
998 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
999 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
1000 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1001 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
1002 Cxx1yLoc))
1003 return false;
1004 }
1005 return true;
1006 }
1007
1008 case Stmt::AttributedStmtClass:
1009 if (!Cxx1yLoc.isValid())
1010 Cxx1yLoc = S->getLocStart();
1011 return true;
1012
1013 case Stmt::IfStmtClass: {
1014 // C++1y allows if-statements.
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017
1018 IfStmt *If = cast<IfStmt>(S);
1019 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1020 Cxx1yLoc))
1021 return false;
1022 if (If->getElse() &&
1023 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1024 Cxx1yLoc))
1025 return false;
1026 return true;
1027 }
1028
1029 case Stmt::WhileStmtClass:
1030 case Stmt::DoStmtClass:
1031 case Stmt::ForStmtClass:
1032 case Stmt::CXXForRangeStmtClass:
1033 case Stmt::ContinueStmtClass:
1034 // C++1y allows all of these. We don't allow them as extensions in C++11,
1035 // because they don't make sense without variable mutation.
1036 if (!SemaRef.getLangOpts().CPlusPlus1y)
1037 break;
1038 if (!Cxx1yLoc.isValid())
1039 Cxx1yLoc = S->getLocStart();
1040 for (Stmt::child_range Children = S->children(); Children; ++Children)
1041 if (*Children &&
1042 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1043 Cxx1yLoc))
1044 return false;
1045 return true;
1046
1047 case Stmt::SwitchStmtClass:
1048 case Stmt::CaseStmtClass:
1049 case Stmt::DefaultStmtClass:
1050 case Stmt::BreakStmtClass:
1051 // C++1y allows switch-statements, and since they don't need variable
1052 // mutation, we can reasonably allow them in C++11 as an extension.
1053 if (!Cxx1yLoc.isValid())
1054 Cxx1yLoc = S->getLocStart();
1055 for (Stmt::child_range Children = S->children(); Children; ++Children)
1056 if (*Children &&
1057 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1058 Cxx1yLoc))
1059 return false;
1060 return true;
1061
1062 default:
1063 if (!isa<Expr>(S))
1064 break;
1065
1066 // C++1y allows expression-statements.
1067 if (!Cxx1yLoc.isValid())
1068 Cxx1yLoc = S->getLocStart();
1069 return true;
1070 }
1071
1072 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1073 << isa<CXXConstructorDecl>(Dcl);
1074 return false;
1075}
1076
Richard Smith9f569cc2011-10-01 02:31:28 +00001077/// Check the body for the given constexpr function declaration only contains
1078/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1079///
1080/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001081bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001082 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001083 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001084 // The definition of a constexpr function shall satisfy the following
1085 // constraints: [...]
1086 // - its function-body shall be = delete, = default, or a
1087 // compound-statement
1088 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001089 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 // In the definition of a constexpr constructor, [...]
1091 // - its function-body shall not be a function-try-block;
1092 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1093 << isa<CXXConstructorDecl>(Dcl);
1094 return false;
1095 }
1096
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001097 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001098
1099 // - its function-body shall be [...] a compound-statement that contains only
1100 // [... list of cases ...]
1101 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1102 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001103 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1104 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001105 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1106 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001107 }
1108
Richard Smitha10b9782013-04-22 15:31:51 +00001109 if (Cxx1yLoc.isValid())
1110 Diag(Cxx1yLoc,
1111 getLangOpts().CPlusPlus1y
1112 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1113 : diag::ext_constexpr_body_invalid_stmt)
1114 << isa<CXXConstructorDecl>(Dcl);
1115
Richard Smith9f569cc2011-10-01 02:31:28 +00001116 if (const CXXConstructorDecl *Constructor
1117 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1118 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001119 // DR1359:
1120 // - every non-variant non-static data member and base class sub-object
1121 // shall be initialized;
1122 // - if the class is a non-empty union, or for each non-empty anonymous
1123 // union member of a non-union class, exactly one non-static data member
1124 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001125 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001126 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001127 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1128 return false;
1129 }
Richard Smith6e433752011-10-10 16:38:04 +00001130 } else if (!Constructor->isDependentContext() &&
1131 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1133
1134 // Skip detailed checking if we have enough initializers, and we would
1135 // allow at most one initializer per member.
1136 bool AnyAnonStructUnionMembers = false;
1137 unsigned Fields = 0;
1138 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1139 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001140 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001141 AnyAnonStructUnionMembers = true;
1142 break;
1143 }
1144 }
1145 if (AnyAnonStructUnionMembers ||
1146 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1147 // Check initialization of non-static data members. Base classes are
1148 // always initialized so do not need to be checked. Dependent bases
1149 // might not have initializers in the member initializer list.
1150 llvm::SmallSet<Decl*, 16> Inits;
1151 for (CXXConstructorDecl::init_const_iterator
1152 I = Constructor->init_begin(), E = Constructor->init_end();
1153 I != E; ++I) {
1154 if (FieldDecl *FD = (*I)->getMember())
1155 Inits.insert(FD);
1156 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1157 Inits.insert(ID->chain_begin(), ID->chain_end());
1158 }
1159
1160 bool Diagnosed = false;
1161 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1162 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001163 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001164 if (Diagnosed)
1165 return false;
1166 }
1167 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001168 } else {
1169 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001170 // C++1y doesn't require constexpr functions to contain a 'return'
1171 // statement. We still do, unless the return type is void, because
1172 // otherwise if there's no return statement, the function cannot
1173 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001174 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001175 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001176 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1177 : diag::err_constexpr_body_no_return);
1178 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001179 }
1180 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001181 Diag(ReturnStmts.back(),
1182 getLangOpts().CPlusPlus1y
1183 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1184 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001185 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1186 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001187 }
1188 }
1189
Richard Smith5ba73e12012-02-04 00:33:54 +00001190 // C++11 [dcl.constexpr]p5:
1191 // if no function argument values exist such that the function invocation
1192 // substitution would produce a constant expression, the program is
1193 // ill-formed; no diagnostic required.
1194 // C++11 [dcl.constexpr]p3:
1195 // - every constructor call and implicit conversion used in initializing the
1196 // return value shall be one of those allowed in a constant expression.
1197 // C++11 [dcl.constexpr]p4:
1198 // - every constructor involved in initializing non-static data members and
1199 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001200 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001201 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001202 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001203 << isa<CXXConstructorDecl>(Dcl);
1204 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1205 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001206 // Don't return false here: we allow this for compatibility in
1207 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001208 }
1209
Richard Smith9f569cc2011-10-01 02:31:28 +00001210 return true;
1211}
1212
Douglas Gregorb48fe382008-10-31 09:07:45 +00001213/// isCurrentClassName - Determine whether the identifier II is the
1214/// name of the class type currently being defined. In the case of
1215/// nested classes, this will only return true if II is the name of
1216/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001217bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1218 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001219 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001220
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001221 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001222 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001223 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001224 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1225 } else
1226 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1227
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001228 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001229 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001230 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001231}
1232
Douglas Gregor229d47a2012-11-10 07:24:09 +00001233/// \brief Determine whether the given class is a base class of the given
1234/// class, including looking at dependent bases.
1235static bool findCircularInheritance(const CXXRecordDecl *Class,
1236 const CXXRecordDecl *Current) {
1237 SmallVector<const CXXRecordDecl*, 8> Queue;
1238
1239 Class = Class->getCanonicalDecl();
1240 while (true) {
1241 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1242 E = Current->bases_end();
1243 I != E; ++I) {
1244 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1245 if (!Base)
1246 continue;
1247
1248 Base = Base->getDefinition();
1249 if (!Base)
1250 continue;
1251
1252 if (Base->getCanonicalDecl() == Class)
1253 return true;
1254
1255 Queue.push_back(Base);
1256 }
1257
1258 if (Queue.empty())
1259 return false;
1260
Robert Wilhelm344472e2013-08-23 16:11:15 +00001261 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001262 }
1263
1264 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001265}
1266
Mike Stump1eb44332009-09-09 15:08:12 +00001267/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001268///
1269/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1270/// and returns NULL otherwise.
1271CXXBaseSpecifier *
1272Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1273 SourceRange SpecifierRange,
1274 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001275 TypeSourceInfo *TInfo,
1276 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001277 QualType BaseType = TInfo->getType();
1278
Douglas Gregor2943aed2009-03-03 04:44:36 +00001279 // C++ [class.union]p1:
1280 // A union shall not have base classes.
1281 if (Class->isUnion()) {
1282 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1283 << SpecifierRange;
1284 return 0;
1285 }
1286
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001287 if (EllipsisLoc.isValid() &&
1288 !TInfo->getType()->containsUnexpandedParameterPack()) {
1289 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1290 << TInfo->getTypeLoc().getSourceRange();
1291 EllipsisLoc = SourceLocation();
1292 }
Douglas Gregord777e282012-11-10 01:18:17 +00001293
1294 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1295
1296 if (BaseType->isDependentType()) {
1297 // Make sure that we don't have circular inheritance among our dependent
1298 // bases. For non-dependent bases, the check for completeness below handles
1299 // this.
1300 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1301 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1302 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001303 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001304 Diag(BaseLoc, diag::err_circular_inheritance)
1305 << BaseType << Context.getTypeDeclType(Class);
1306
1307 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1308 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1309 << BaseType;
1310
1311 return 0;
1312 }
1313 }
1314
Mike Stump1eb44332009-09-09 15:08:12 +00001315 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001316 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001317 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001318 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001319
1320 // Base specifiers must be record types.
1321 if (!BaseType->isRecordType()) {
1322 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1323 return 0;
1324 }
1325
1326 // C++ [class.union]p1:
1327 // A union shall not be used as a base class.
1328 if (BaseType->isUnionType()) {
1329 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1330 return 0;
1331 }
1332
1333 // C++ [class.derived]p2:
1334 // The class-name in a base-specifier shall not be an incompletely
1335 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001336 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001337 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001338 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001339 return 0;
John McCall572fc622010-08-17 07:23:57 +00001340 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001341
Eli Friedman1d954f62009-08-15 21:55:26 +00001342 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001343 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001344 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001345 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001346 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001347 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001348 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001349
Anders Carlsson1d209272011-03-25 14:55:14 +00001350 // C++ [class]p3:
1351 // If a class is marked final and it appears as a base-type-specifier in
1352 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001353 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001354 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1355 << CXXBaseDecl->getDeclName();
1356 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1357 << CXXBaseDecl->getDeclName();
1358 return 0;
1359 }
1360
John McCall572fc622010-08-17 07:23:57 +00001361 if (BaseDecl->isInvalidDecl())
1362 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001363
1364 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001365 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001366 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001367 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001368}
1369
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001370/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1371/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001372/// example:
1373/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001374/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001375BaseResult
John McCalld226f652010-08-21 09:40:31 +00001376Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001377 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001378 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379 ParsedType basetype, SourceLocation BaseLoc,
1380 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001381 if (!classdecl)
1382 return true;
1383
Douglas Gregor40808ce2009-03-09 23:48:35 +00001384 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001385 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001386 if (!Class)
1387 return true;
1388
Richard Smith05321402013-02-19 23:47:15 +00001389 // We do not support any C++11 attributes on base-specifiers yet.
1390 // Diagnose any attributes we see.
1391 if (!Attributes.empty()) {
1392 for (AttributeList *Attr = Attributes.getList(); Attr;
1393 Attr = Attr->getNext()) {
1394 if (Attr->isInvalid() ||
1395 Attr->getKind() == AttributeList::IgnoredAttribute)
1396 continue;
1397 Diag(Attr->getLoc(),
1398 Attr->getKind() == AttributeList::UnknownAttribute
1399 ? diag::warn_unknown_attribute_ignored
1400 : diag::err_base_specifier_attribute)
1401 << Attr->getName();
1402 }
1403 }
1404
Nick Lewycky56062202010-07-26 16:56:01 +00001405 TypeSourceInfo *TInfo = 0;
1406 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001407
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001408 if (EllipsisLoc.isInvalid() &&
1409 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001410 UPPC_BaseType))
1411 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001412
Douglas Gregor2943aed2009-03-03 04:44:36 +00001413 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001414 Virtual, Access, TInfo,
1415 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001416 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001417 else
1418 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Douglas Gregor2943aed2009-03-03 04:44:36 +00001420 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001421}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001422
Douglas Gregor2943aed2009-03-03 04:44:36 +00001423/// \brief Performs the actual work of attaching the given base class
1424/// specifiers to a C++ class.
1425bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1426 unsigned NumBases) {
1427 if (NumBases == 0)
1428 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001429
1430 // Used to keep track of which base types we have already seen, so
1431 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001432 // that the key is always the unqualified canonical type of the base
1433 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001434 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1435
1436 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001437 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001438 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001439 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001440 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001441 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001442 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001443
1444 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1445 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001446 // C++ [class.mi]p3:
1447 // A class shall not be specified as a direct base class of a
1448 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001449 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001450 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001451 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001452 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001453
1454 // Delete the duplicate base class specifier; we're going to
1455 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001456 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001457
1458 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001459 } else {
1460 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001461 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001462 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001463 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1464 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1465 if (Class->isInterface() &&
1466 (!RD->isInterface() ||
1467 KnownBase->getAccessSpecifier() != AS_public)) {
1468 // The Microsoft extension __interface does not permit bases that
1469 // are not themselves public interfaces.
1470 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1471 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1472 << RD->getSourceRange();
1473 Invalid = true;
1474 }
1475 if (RD->hasAttr<WeakAttr>())
1476 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1477 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001478 }
1479 }
1480
1481 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001482 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001483
1484 // Delete the remaining (good) base class specifiers, since their
1485 // data has been copied into the CXXRecordDecl.
1486 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001487 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001488
1489 return Invalid;
1490}
1491
1492/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1493/// class, after checking whether there are any duplicate base
1494/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001495void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001496 unsigned NumBases) {
1497 if (!ClassDecl || !Bases || !NumBases)
1498 return;
1499
1500 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001501 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001502}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001503
Douglas Gregora8f32e02009-10-06 17:59:45 +00001504/// \brief Determine whether the type \p Derived is a C++ class that is
1505/// derived from the type \p Base.
1506bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001507 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001508 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001509
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001510 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001511 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001512 return false;
1513
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001514 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001515 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001516 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001517
1518 // If either the base or the derived type is invalid, don't try to
1519 // check whether one is derived from the other.
1520 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1521 return false;
1522
John McCall86ff3082010-02-04 22:26:26 +00001523 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1524 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001525}
1526
1527/// \brief Determine whether the type \p Derived is a C++ class that is
1528/// derived from the type \p Base.
1529bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001530 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001531 return false;
1532
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001533 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001534 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001535 return false;
1536
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001537 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001538 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001539 return false;
1540
Douglas Gregora8f32e02009-10-06 17:59:45 +00001541 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1542}
1543
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001544void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001545 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001546 assert(BasePathArray.empty() && "Base path array must be empty!");
1547 assert(Paths.isRecordingPaths() && "Must record paths!");
1548
1549 const CXXBasePath &Path = Paths.front();
1550
1551 // We first go backward and check if we have a virtual base.
1552 // FIXME: It would be better if CXXBasePath had the base specifier for
1553 // the nearest virtual base.
1554 unsigned Start = 0;
1555 for (unsigned I = Path.size(); I != 0; --I) {
1556 if (Path[I - 1].Base->isVirtual()) {
1557 Start = I - 1;
1558 break;
1559 }
1560 }
1561
1562 // Now add all bases.
1563 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001564 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001565}
1566
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001567/// \brief Determine whether the given base path includes a virtual
1568/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001569bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1570 for (CXXCastPath::const_iterator B = BasePath.begin(),
1571 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001572 B != BEnd; ++B)
1573 if ((*B)->isVirtual())
1574 return true;
1575
1576 return false;
1577}
1578
Douglas Gregora8f32e02009-10-06 17:59:45 +00001579/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1580/// conversion (where Derived and Base are class types) is
1581/// well-formed, meaning that the conversion is unambiguous (and
1582/// that all of the base classes are accessible). Returns true
1583/// and emits a diagnostic if the code is ill-formed, returns false
1584/// otherwise. Loc is the location where this routine should point to
1585/// if there is an error, and Range is the source range to highlight
1586/// if there is an error.
1587bool
1588Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001589 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001590 unsigned AmbigiousBaseConvID,
1591 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001592 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001593 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001594 // First, determine whether the path from Derived to Base is
1595 // ambiguous. This is slightly more expensive than checking whether
1596 // the Derived to Base conversion exists, because here we need to
1597 // explore multiple paths to determine if there is an ambiguity.
1598 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1599 /*DetectVirtual=*/false);
1600 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1601 assert(DerivationOkay &&
1602 "Can only be used with a derived-to-base conversion");
1603 (void)DerivationOkay;
1604
1605 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001606 if (InaccessibleBaseID) {
1607 // Check that the base class can be accessed.
1608 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1609 InaccessibleBaseID)) {
1610 case AR_inaccessible:
1611 return true;
1612 case AR_accessible:
1613 case AR_dependent:
1614 case AR_delayed:
1615 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001616 }
John McCall6b2accb2010-02-10 09:31:12 +00001617 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001618
1619 // Build a base path if necessary.
1620 if (BasePath)
1621 BuildBasePathArray(Paths, *BasePath);
1622 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001623 }
1624
David Majnemer2f686692013-06-22 06:43:58 +00001625 if (AmbigiousBaseConvID) {
1626 // We know that the derived-to-base conversion is ambiguous, and
1627 // we're going to produce a diagnostic. Perform the derived-to-base
1628 // search just one more time to compute all of the possible paths so
1629 // that we can print them out. This is more expensive than any of
1630 // the previous derived-to-base checks we've done, but at this point
1631 // performance isn't as much of an issue.
1632 Paths.clear();
1633 Paths.setRecordingPaths(true);
1634 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1635 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1636 (void)StillOkay;
1637
1638 // Build up a textual representation of the ambiguous paths, e.g.,
1639 // D -> B -> A, that will be used to illustrate the ambiguous
1640 // conversions in the diagnostic. We only print one of the paths
1641 // to each base class subobject.
1642 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1643
1644 Diag(Loc, AmbigiousBaseConvID)
1645 << Derived << Base << PathDisplayStr << Range << Name;
1646 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 return true;
1648}
1649
1650bool
1651Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001652 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001653 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001654 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001655 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001656 IgnoreAccess ? 0
1657 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001658 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001659 Loc, Range, DeclarationName(),
1660 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001661}
1662
1663
1664/// @brief Builds a string representing ambiguous paths from a
1665/// specific derived class to different subobjects of the same base
1666/// class.
1667///
1668/// This function builds a string that can be used in error messages
1669/// to show the different paths that one can take through the
1670/// inheritance hierarchy to go from the derived class to different
1671/// subobjects of a base class. The result looks something like this:
1672/// @code
1673/// struct D -> struct B -> struct A
1674/// struct D -> struct C -> struct A
1675/// @endcode
1676std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1677 std::string PathDisplayStr;
1678 std::set<unsigned> DisplayedPaths;
1679 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1680 Path != Paths.end(); ++Path) {
1681 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1682 // We haven't displayed a path to this particular base
1683 // class subobject yet.
1684 PathDisplayStr += "\n ";
1685 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1686 for (CXXBasePath::const_iterator Element = Path->begin();
1687 Element != Path->end(); ++Element)
1688 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1689 }
1690 }
1691
1692 return PathDisplayStr;
1693}
1694
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001695//===----------------------------------------------------------------------===//
1696// C++ class member Handling
1697//===----------------------------------------------------------------------===//
1698
Abramo Bagnara6206d532010-06-05 05:09:32 +00001699/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001700bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1701 SourceLocation ASLoc,
1702 SourceLocation ColonLoc,
1703 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001704 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001705 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001706 ASLoc, ColonLoc);
1707 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001708 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001709}
1710
Richard Smitha4b39652012-08-06 03:25:17 +00001711/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001712void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001713 if (D->isInvalidDecl())
1714 return;
1715
Eli Friedmandae92712013-09-05 23:51:03 +00001716 // We only care about "override" and "final" declarations.
1717 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1718 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719
Eli Friedmandae92712013-09-05 23:51:03 +00001720 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001721
Eli Friedmandae92712013-09-05 23:51:03 +00001722 // We can't check dependent instance methods.
1723 if (MD && MD->isInstance() &&
1724 (MD->getParent()->hasAnyDependentBases() ||
1725 MD->getType()->isDependentType()))
1726 return;
1727
1728 if (MD && !MD->isVirtual()) {
1729 // If we have a non-virtual method, check if if hides a virtual method.
1730 // (In that case, it's most likely the method has the wrong type.)
1731 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1732 FindHiddenVirtualMethods(MD, OverloadedMethods);
1733
1734 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001735 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1736 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001737 diag::override_keyword_hides_virtual_member_function)
1738 << "override" << (OverloadedMethods.size() > 1);
1739 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001740 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001741 diag::override_keyword_hides_virtual_member_function)
1742 << "final" << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001743 }
Eli Friedmandae92712013-09-05 23:51:03 +00001744 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1745 MD->setInvalidDecl();
1746 return;
1747 }
1748 // Fall through into the general case diagnostic.
1749 // FIXME: We might want to attempt typo correction here.
1750 }
1751
1752 if (!MD || !MD->isVirtual()) {
1753 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1754 Diag(OA->getLocation(),
1755 diag::override_keyword_only_allowed_on_virtual_member_functions)
1756 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1757 D->dropAttr<OverrideAttr>();
1758 }
1759 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1760 Diag(FA->getLocation(),
1761 diag::override_keyword_only_allowed_on_virtual_member_functions)
1762 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1763 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001764 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001765 return;
1766 }
Richard Smitha4b39652012-08-06 03:25:17 +00001767
Richard Smitha4b39652012-08-06 03:25:17 +00001768 // C++11 [class.virtual]p5:
1769 // If a virtual function is marked with the virt-specifier override and
1770 // does not override a member function of a base class, the program is
1771 // ill-formed.
1772 bool HasOverriddenMethods =
1773 MD->begin_overridden_methods() != MD->end_overridden_methods();
1774 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1775 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1776 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001777}
1778
Richard Smitha4b39652012-08-06 03:25:17 +00001779/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001780/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001781/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001782bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1783 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001784 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001785 return false;
1786
1787 Diag(New->getLocation(), diag::err_final_function_overridden)
1788 << New->getDeclName();
1789 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1790 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001791}
1792
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001793static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001794 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1795 // FIXME: Destruction of ObjC lifetime types has side-effects.
1796 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1797 return !RD->isCompleteDefinition() ||
1798 !RD->hasTrivialDefaultConstructor() ||
1799 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001800 return false;
1801}
1802
John McCall76da55d2013-04-16 07:28:30 +00001803static AttributeList *getMSPropertyAttr(AttributeList *list) {
1804 for (AttributeList* it = list; it != 0; it = it->getNext())
1805 if (it->isDeclspecPropertyAttribute())
1806 return it;
1807 return 0;
1808}
1809
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001810/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1811/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001812/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001813/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1814/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001815NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001816Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001817 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001818 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001819 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001820 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001821 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1822 DeclarationName Name = NameInfo.getName();
1823 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001824
1825 // For anonymous bitfields, the location should point to the type.
1826 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001827 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001828
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001829 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001830
John McCall4bde1e12010-06-04 08:34:12 +00001831 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001832 assert(!DS.isFriendSpecified());
1833
Richard Smith1ab0d902011-06-25 02:28:38 +00001834 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001835
John McCalle402e722012-09-25 07:32:39 +00001836 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1837 // The Microsoft extension __interface only permits public member functions
1838 // and prohibits constructors, destructors, operators, non-public member
1839 // functions, static methods and data members.
1840 unsigned InvalidDecl;
1841 bool ShowDeclName = true;
1842 if (!isFunc)
1843 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1844 else if (AS != AS_public)
1845 InvalidDecl = 2;
1846 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1847 InvalidDecl = 3;
1848 else switch (Name.getNameKind()) {
1849 case DeclarationName::CXXConstructorName:
1850 InvalidDecl = 4;
1851 ShowDeclName = false;
1852 break;
1853
1854 case DeclarationName::CXXDestructorName:
1855 InvalidDecl = 5;
1856 ShowDeclName = false;
1857 break;
1858
1859 case DeclarationName::CXXOperatorName:
1860 case DeclarationName::CXXConversionFunctionName:
1861 InvalidDecl = 6;
1862 break;
1863
1864 default:
1865 InvalidDecl = 0;
1866 break;
1867 }
1868
1869 if (InvalidDecl) {
1870 if (ShowDeclName)
1871 Diag(Loc, diag::err_invalid_member_in_interface)
1872 << (InvalidDecl-1) << Name;
1873 else
1874 Diag(Loc, diag::err_invalid_member_in_interface)
1875 << (InvalidDecl-1) << "";
1876 return 0;
1877 }
1878 }
1879
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001880 // C++ 9.2p6: A member shall not be declared to have automatic storage
1881 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001882 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1883 // data members and cannot be applied to names declared const or static,
1884 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001885 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001886 case DeclSpec::SCS_unspecified:
1887 case DeclSpec::SCS_typedef:
1888 case DeclSpec::SCS_static:
1889 break;
1890 case DeclSpec::SCS_mutable:
1891 if (isFunc) {
1892 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Richard Smithec642442013-04-12 22:46:28 +00001894 // FIXME: It would be nicer if the keyword was ignored only for this
1895 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001896 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001897 }
1898 break;
1899 default:
1900 Diag(DS.getStorageClassSpecLoc(),
1901 diag::err_storageclass_invalid_for_member);
1902 D.getMutableDeclSpec().ClearStorageClassSpecs();
1903 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001904 }
1905
Sebastian Redl669d5d72008-11-14 23:42:31 +00001906 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1907 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001908 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001909
David Blaikie1d87fba2013-01-30 01:22:18 +00001910 if (DS.isConstexprSpecified() && isInstField) {
1911 SemaDiagnosticBuilder B =
1912 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1913 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1914 if (InitStyle == ICIS_NoInit) {
1915 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1916 D.getMutableDeclSpec().ClearConstexprSpec();
1917 const char *PrevSpec;
1918 unsigned DiagID;
1919 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1920 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001921 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001922 assert(!Failed && "Making a constexpr member const shouldn't fail");
1923 } else {
1924 B << 1;
1925 const char *PrevSpec;
1926 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001927 if (D.getMutableDeclSpec().SetStorageClassSpec(
1928 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001929 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001930 "This is the only DeclSpec that should fail to be applied");
1931 B << 1;
1932 } else {
1933 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1934 isInstField = false;
1935 }
1936 }
1937 }
1938
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001939 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001940 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001941 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001942
1943 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001944 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001945 Diag(Loc, diag::err_bad_variable_name)
1946 << Name;
1947 return 0;
1948 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001949
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001950 IdentifierInfo *II = Name.getAsIdentifierInfo();
1951
Douglas Gregorf2503652011-09-21 14:40:46 +00001952 // Member field could not be with "template" keyword.
1953 // So TemplateParameterLists should be empty in this case.
1954 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001955 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001956 if (TemplateParams->size()) {
1957 // There is no such thing as a member field template.
1958 Diag(D.getIdentifierLoc(), diag::err_template_member)
1959 << II
1960 << SourceRange(TemplateParams->getTemplateLoc(),
1961 TemplateParams->getRAngleLoc());
1962 } else {
1963 // There is an extraneous 'template<>' for this member.
1964 Diag(TemplateParams->getTemplateLoc(),
1965 diag::err_template_member_noparams)
1966 << II
1967 << SourceRange(TemplateParams->getTemplateLoc(),
1968 TemplateParams->getRAngleLoc());
1969 }
1970 return 0;
1971 }
1972
Douglas Gregor922fff22010-10-13 22:19:53 +00001973 if (SS.isSet() && !SS.isInvalid()) {
1974 // The user provided a superfluous scope specifier inside a class
1975 // definition:
1976 //
1977 // class X {
1978 // int X::member;
1979 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001980 if (DeclContext *DC = computeDeclContext(SS, false))
1981 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001982 else
1983 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1984 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001985
Douglas Gregor922fff22010-10-13 22:19:53 +00001986 SS.clear();
1987 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001988
John McCall76da55d2013-04-16 07:28:30 +00001989 AttributeList *MSPropertyAttr =
1990 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001991 if (MSPropertyAttr) {
1992 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1993 BitWidth, InitStyle, AS, MSPropertyAttr);
1994 if (!Member)
1995 return 0;
1996 isInstField = false;
1997 } else {
1998 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1999 BitWidth, InitStyle, AS);
2000 assert(Member && "HandleField never returns null");
2001 }
2002 } else {
2003 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2004
2005 Member = HandleDeclarator(S, D, TemplateParameterLists);
2006 if (!Member)
2007 return 0;
2008
2009 // Non-instance-fields can't have a bitfield.
2010 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002011 if (Member->isInvalidDecl()) {
2012 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002013 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002014 // C++ 9.6p3: A bit-field shall not be a static member.
2015 // "static member 'A' cannot be a bit-field"
2016 Diag(Loc, diag::err_static_not_bitfield)
2017 << Name << BitWidth->getSourceRange();
2018 } else if (isa<TypedefDecl>(Member)) {
2019 // "typedef member 'x' cannot be a bit-field"
2020 Diag(Loc, diag::err_typedef_not_bitfield)
2021 << Name << BitWidth->getSourceRange();
2022 } else {
2023 // A function typedef ("typedef int f(); f a;").
2024 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2025 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002026 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002027 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Chris Lattner8b963ef2009-03-05 23:01:03 +00002030 BitWidth = 0;
2031 Member->setInvalidDecl();
2032 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002033
2034 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Larisse Voufoef4579c2013-08-06 01:03:05 +00002036 // If we have declared a member function template or static data member
2037 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002038 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2039 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002040 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2041 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002042 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002043
Richard Smitha4b39652012-08-06 03:25:17 +00002044 if (VS.isOverrideSpecified())
2045 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2046 if (VS.isFinalSpecified())
2047 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002048
Douglas Gregorf5251602011-03-08 17:10:18 +00002049 if (VS.getLastLocation().isValid()) {
2050 // Update the end location of a method that has a virt-specifiers.
2051 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2052 MD->setRangeEnd(VS.getLastLocation());
2053 }
Richard Smitha4b39652012-08-06 03:25:17 +00002054
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002055 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002056
Douglas Gregor10bd3682008-11-17 22:58:34 +00002057 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002058
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002059 if (isInstField) {
2060 FieldDecl *FD = cast<FieldDecl>(Member);
2061 FieldCollector->Add(FD);
2062
2063 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2064 FD->getLocation())
2065 != DiagnosticsEngine::Ignored) {
2066 // Remember all explicit private FieldDecls that have a name, no side
2067 // effects and are not part of a dependent type declaration.
2068 if (!FD->isImplicit() && FD->getDeclName() &&
2069 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002070 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002071 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002072 !InitializationHasSideEffects(*FD))
2073 UnusedPrivateFields.insert(FD);
2074 }
2075 }
2076
John McCalld226f652010-08-21 09:40:31 +00002077 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002078}
2079
Hans Wennborg471f9852012-09-18 15:58:06 +00002080namespace {
2081 class UninitializedFieldVisitor
2082 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2083 Sema &S;
2084 ValueDecl *VD;
Richard Trieufbb08b52013-09-13 03:20:53 +00002085 bool isReferenceType;
Hans Wennborg471f9852012-09-18 15:58:06 +00002086 public:
2087 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2088 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002089 S(S) {
2090 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2091 this->VD = IFD->getAnonField();
2092 else
2093 this->VD = VD;
Richard Trieufbb08b52013-09-13 03:20:53 +00002094 isReferenceType = this->VD->getType()->isReferenceType();
Hans Wennborg471f9852012-09-18 15:58:06 +00002095 }
2096
Richard Trieu3ddec882013-09-16 20:46:50 +00002097 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2098 if (CheckReferenceOnly && !isReferenceType)
2099 return;
2100
Richard Trieufbb08b52013-09-13 03:20:53 +00002101 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2102 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002103
Richard Trieufbb08b52013-09-13 03:20:53 +00002104 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2105 // or union.
2106 MemberExpr *FieldME = ME;
2107
2108 Expr *Base = ME;
2109 while (isa<MemberExpr>(Base)) {
2110 ME = cast<MemberExpr>(Base);
2111
2112 if (isa<VarDecl>(ME->getMemberDecl()))
2113 return;
2114
2115 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2116 if (!FD->isAnonymousStructOrUnion())
2117 FieldME = ME;
2118
2119 Base = ME->getBase();
2120 }
2121
Richard Trieu3ddec882013-09-16 20:46:50 +00002122 if (!isa<CXXThisExpr>(Base))
2123 return;
2124
2125 if (VD == FieldME->getMemberDecl()) {
2126 unsigned diag = isReferenceType
Richard Trieufbb08b52013-09-13 03:20:53 +00002127 ? diag::warn_reference_field_is_uninit
2128 : diag::warn_field_is_uninit;
2129 S.Diag(FieldME->getExprLoc(), diag) << VD;
2130 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002131 }
2132
2133 void HandleValue(Expr *E) {
2134 E = E->IgnoreParens();
2135
2136 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002137 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002138 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002139 }
2140
2141 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2142 HandleValue(CO->getTrueExpr());
2143 HandleValue(CO->getFalseExpr());
2144 return;
2145 }
2146
2147 if (BinaryConditionalOperator *BCO =
2148 dyn_cast<BinaryConditionalOperator>(E)) {
2149 HandleValue(BCO->getCommon());
2150 HandleValue(BCO->getFalseExpr());
2151 return;
2152 }
2153
2154 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2155 switch (BO->getOpcode()) {
2156 default:
2157 return;
2158 case(BO_PtrMemD):
2159 case(BO_PtrMemI):
2160 HandleValue(BO->getLHS());
2161 return;
2162 case(BO_Comma):
2163 HandleValue(BO->getRHS());
2164 return;
2165 }
2166 }
2167 }
2168
Richard Trieufbb08b52013-09-13 03:20:53 +00002169 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002170 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002171
2172 Inherited::VisitMemberExpr(ME);
2173 }
2174
Hans Wennborg471f9852012-09-18 15:58:06 +00002175 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2176 if (E->getCastKind() == CK_LValueToRValue)
2177 HandleValue(E->getSubExpr());
2178
2179 Inherited::VisitImplicitCastExpr(E);
2180 }
2181
Richard Trieufbb08b52013-09-13 03:20:53 +00002182 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2183 if (E->getNumArgs() == 1)
2184 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2185 if (ICE->getCastKind() == CK_NoOp)
2186 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002187 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002188
2189 Inherited::VisitCXXConstructExpr(E);
2190 }
2191
Hans Wennborg471f9852012-09-18 15:58:06 +00002192 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2193 Expr *Callee = E->getCallee();
2194 if (isa<MemberExpr>(Callee))
2195 HandleValue(Callee);
2196
2197 Inherited::VisitCXXMemberCallExpr(E);
2198 }
2199 };
2200 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2201 ValueDecl *VD) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002202 if (E)
2203 UninitializedFieldVisitor(S, VD).Visit(E);
Hans Wennborg471f9852012-09-18 15:58:06 +00002204 }
2205} // namespace
2206
Richard Smith7a614d82011-06-11 17:19:42 +00002207/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002208/// in-class initializer for a non-static C++ class member, and after
2209/// instantiating an in-class initializer in a class template. Such actions
2210/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002211void
Richard Smithca523302012-06-10 03:12:00 +00002212Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002213 Expr *InitExpr) {
2214 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002215 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2216 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002217
2218 if (!InitExpr) {
2219 FD->setInvalidDecl();
2220 FD->removeInClassInitializer();
2221 return;
2222 }
2223
Peter Collingbournefef21892011-10-23 18:59:44 +00002224 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2225 FD->setInvalidDecl();
2226 FD->removeInClassInitializer();
2227 return;
2228 }
2229
Richard Smith7a614d82011-06-11 17:19:42 +00002230 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002231 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002232 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002233 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002234 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002235 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002236 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2237 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002238 if (Init.isInvalid()) {
2239 FD->setInvalidDecl();
2240 return;
2241 }
Richard Smith7a614d82011-06-11 17:19:42 +00002242 }
2243
Richard Smith41956372013-01-14 22:39:08 +00002244 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002245 // The initialization of each base and member constitutes a
2246 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002247 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002248 if (Init.isInvalid()) {
2249 FD->setInvalidDecl();
2250 return;
2251 }
2252
2253 InitExpr = Init.release();
2254
Richard Trieufbb08b52013-09-13 03:20:53 +00002255 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2256 != DiagnosticsEngine::Ignored) {
2257 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2258 }
2259
Richard Smith7a614d82011-06-11 17:19:42 +00002260 FD->setInClassInitializer(InitExpr);
2261}
2262
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002263/// \brief Find the direct and/or virtual base specifiers that
2264/// correspond to the given base type, for use in base initialization
2265/// within a constructor.
2266static bool FindBaseInitializer(Sema &SemaRef,
2267 CXXRecordDecl *ClassDecl,
2268 QualType BaseType,
2269 const CXXBaseSpecifier *&DirectBaseSpec,
2270 const CXXBaseSpecifier *&VirtualBaseSpec) {
2271 // First, check for a direct base class.
2272 DirectBaseSpec = 0;
2273 for (CXXRecordDecl::base_class_const_iterator Base
2274 = ClassDecl->bases_begin();
2275 Base != ClassDecl->bases_end(); ++Base) {
2276 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2277 // We found a direct base of this type. That's what we're
2278 // initializing.
2279 DirectBaseSpec = &*Base;
2280 break;
2281 }
2282 }
2283
2284 // Check for a virtual base class.
2285 // FIXME: We might be able to short-circuit this if we know in advance that
2286 // there are no virtual bases.
2287 VirtualBaseSpec = 0;
2288 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2289 // We haven't found a base yet; search the class hierarchy for a
2290 // virtual base class.
2291 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2292 /*DetectVirtual=*/false);
2293 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2294 BaseType, Paths)) {
2295 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2296 Path != Paths.end(); ++Path) {
2297 if (Path->back().Base->isVirtual()) {
2298 VirtualBaseSpec = Path->back().Base;
2299 break;
2300 }
2301 }
2302 }
2303 }
2304
2305 return DirectBaseSpec || VirtualBaseSpec;
2306}
2307
Sebastian Redl6df65482011-09-24 17:48:25 +00002308/// \brief Handle a C++ member initializer using braced-init-list syntax.
2309MemInitResult
2310Sema::ActOnMemInitializer(Decl *ConstructorD,
2311 Scope *S,
2312 CXXScopeSpec &SS,
2313 IdentifierInfo *MemberOrBase,
2314 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002315 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002316 SourceLocation IdLoc,
2317 Expr *InitList,
2318 SourceLocation EllipsisLoc) {
2319 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002320 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002321 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002322}
2323
2324/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002325MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002326Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002327 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002328 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002329 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002330 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002331 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002332 SourceLocation IdLoc,
2333 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002334 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002335 SourceLocation RParenLoc,
2336 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002337 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002338 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002339 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002341}
2342
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002343namespace {
2344
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002345// Callback to only accept typo corrections that can be a valid C++ member
2346// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002347class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002348public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002349 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2350 : ClassDecl(ClassDecl) {}
2351
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002352 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002353 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2354 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2355 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002356 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002357 }
2358 return false;
2359 }
2360
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002361private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002362 CXXRecordDecl *ClassDecl;
2363};
2364
2365}
2366
Sebastian Redl6df65482011-09-24 17:48:25 +00002367/// \brief Handle a C++ member initializer.
2368MemInitResult
2369Sema::BuildMemInitializer(Decl *ConstructorD,
2370 Scope *S,
2371 CXXScopeSpec &SS,
2372 IdentifierInfo *MemberOrBase,
2373 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002374 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002375 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002376 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002377 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002378 if (!ConstructorD)
2379 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002381 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002382
2383 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002384 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002385 if (!Constructor) {
2386 // The user wrote a constructor initializer on a function that is
2387 // not a C++ constructor. Ignore the error for now, because we may
2388 // have more member initializers coming; we'll diagnose it just
2389 // once in ActOnMemInitializers.
2390 return true;
2391 }
2392
2393 CXXRecordDecl *ClassDecl = Constructor->getParent();
2394
2395 // C++ [class.base.init]p2:
2396 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002397 // constructor's class and, if not found in that scope, are looked
2398 // up in the scope containing the constructor's definition.
2399 // [Note: if the constructor's class contains a member with the
2400 // same name as a direct or virtual base class of the class, a
2401 // mem-initializer-id naming the member or base class and composed
2402 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002403 // mem-initializer-id for the hidden base class may be specified
2404 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002405 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002406 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002407 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002408 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002409 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002410 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002411 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2412 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002413 if (EllipsisLoc.isValid())
2414 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002415 << MemberOrBase
2416 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002417
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002418 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002419 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002420 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002421 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002422 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002423 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002424 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002425
2426 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002427 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002428 } else if (DS.getTypeSpecType() == TST_decltype) {
2429 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002430 } else {
2431 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2432 LookupParsedName(R, S, &SS);
2433
2434 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2435 if (!TyD) {
2436 if (R.isAmbiguous()) return true;
2437
John McCallfd225442010-04-09 19:01:14 +00002438 // We don't want access-control diagnostics here.
2439 R.suppressDiagnostics();
2440
Douglas Gregor7a886e12010-01-19 06:46:48 +00002441 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2442 bool NotUnknownSpecialization = false;
2443 DeclContext *DC = computeDeclContext(SS, false);
2444 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2445 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2446
2447 if (!NotUnknownSpecialization) {
2448 // When the scope specifier can refer to a member of an unknown
2449 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002450 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2451 SS.getWithLocInContext(Context),
2452 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002453 if (BaseType.isNull())
2454 return true;
2455
Douglas Gregor7a886e12010-01-19 06:46:48 +00002456 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002457 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002458 }
2459 }
2460
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002461 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002462 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002463 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002464 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002465 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002466 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002467 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002468 // We have found a non-static data member with a similar
2469 // name to what was typed; complain and initialize that
2470 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002471 diagnoseTypo(Corr,
2472 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2473 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002474 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002475 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002476 const CXXBaseSpecifier *DirectBaseSpec;
2477 const CXXBaseSpecifier *VirtualBaseSpec;
2478 if (FindBaseInitializer(*this, ClassDecl,
2479 Context.getTypeDeclType(Type),
2480 DirectBaseSpec, VirtualBaseSpec)) {
2481 // We have found a direct or virtual base class with a
2482 // similar name to what was typed; complain and initialize
2483 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002484 diagnoseTypo(Corr,
2485 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2486 << MemberOrBase << false,
2487 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002488
Richard Smith2d670972013-08-17 00:46:16 +00002489 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2490 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002491 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002492 diag::note_base_class_specified_here)
2493 << BaseSpec->getType()
2494 << BaseSpec->getSourceRange();
2495
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002496 TyD = Type;
2497 }
2498 }
2499 }
2500
Douglas Gregor7a886e12010-01-19 06:46:48 +00002501 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002502 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002503 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002504 return true;
2505 }
John McCall2b194412009-12-21 10:41:20 +00002506 }
2507
Douglas Gregor7a886e12010-01-19 06:46:48 +00002508 if (BaseType.isNull()) {
2509 BaseType = Context.getTypeDeclType(TyD);
2510 if (SS.isSet()) {
2511 NestedNameSpecifier *Qualifier =
2512 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002513
Douglas Gregor7a886e12010-01-19 06:46:48 +00002514 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002515 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002516 }
John McCall2b194412009-12-21 10:41:20 +00002517 }
2518 }
Mike Stump1eb44332009-09-09 15:08:12 +00002519
John McCalla93c9342009-12-07 02:54:59 +00002520 if (!TInfo)
2521 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002522
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002523 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002524}
2525
Chandler Carruth81c64772011-09-03 01:14:15 +00002526/// Checks a member initializer expression for cases where reference (or
2527/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002528static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2529 Expr *Init,
2530 SourceLocation IdLoc) {
2531 QualType MemberTy = Member->getType();
2532
2533 // We only handle pointers and references currently.
2534 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2535 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2536 return;
2537
2538 const bool IsPointer = MemberTy->isPointerType();
2539 if (IsPointer) {
2540 if (const UnaryOperator *Op
2541 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2542 // The only case we're worried about with pointers requires taking the
2543 // address.
2544 if (Op->getOpcode() != UO_AddrOf)
2545 return;
2546
2547 Init = Op->getSubExpr();
2548 } else {
2549 // We only handle address-of expression initializers for pointers.
2550 return;
2551 }
2552 }
2553
Richard Smitha4bb99c2013-06-12 21:51:50 +00002554 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002555 // We only warn when referring to a non-reference parameter declaration.
2556 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2557 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002558 return;
2559
2560 S.Diag(Init->getExprLoc(),
2561 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2562 : diag::warn_bind_ref_member_to_parameter)
2563 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002564 } else {
2565 // Other initializers are fine.
2566 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002567 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002568
2569 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2570 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002571}
2572
John McCallf312b1e2010-08-26 23:41:50 +00002573MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002574Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002575 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002576 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2577 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2578 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002579 "Member must be a FieldDecl or IndirectFieldDecl");
2580
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002581 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002582 return true;
2583
Douglas Gregor464b2f02010-11-05 22:21:31 +00002584 if (Member->isInvalidDecl())
2585 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002586
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002587 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002588 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002589 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002590 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002591 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002592 } else {
2593 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002594 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002595 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002596
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002597 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002598
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002599 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002600 // Can't check initialization for a member of dependent type or when
2601 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002602 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002603 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002604 bool InitList = false;
2605 if (isa<InitListExpr>(Init)) {
2606 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002607 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002608 }
2609
Chandler Carruth894aed92010-12-06 09:23:57 +00002610 // Initialize the member.
2611 InitializedEntity MemberEntity =
2612 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2613 : InitializedEntity::InitializeMember(IndirectMember, 0);
2614 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002615 InitList ? InitializationKind::CreateDirectList(IdLoc)
2616 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2617 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002618
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002619 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2620 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002621 if (MemberInit.isInvalid())
2622 return true;
2623
Richard Smith8a07cd32013-06-12 20:42:33 +00002624 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2625
Richard Smith41956372013-01-14 22:39:08 +00002626 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002627 // The initialization of each base and member constitutes a
2628 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002629 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002630 if (MemberInit.isInvalid())
2631 return true;
2632
Richard Smithc83c2302012-12-19 01:39:02 +00002633 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002634 }
2635
Chandler Carruth894aed92010-12-06 09:23:57 +00002636 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002637 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2638 InitRange.getBegin(), Init,
2639 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002640 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002641 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2642 InitRange.getBegin(), Init,
2643 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002644 }
Eli Friedman59c04372009-07-29 19:44:27 +00002645}
2646
John McCallf312b1e2010-08-26 23:41:50 +00002647MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002648Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002649 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002650 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002651 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002652 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002653 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002654 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002655
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002656 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002657 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002658 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2659 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002660 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002661 }
2662
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002664 // Initialize the object.
2665 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2666 QualType(ClassDecl->getTypeForDecl(), 0));
2667 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002668 InitList ? InitializationKind::CreateDirectList(NameLoc)
2669 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2670 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002671 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002672 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002673 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002674 if (DelegationInit.isInvalid())
2675 return true;
2676
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002677 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2678 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002679
Richard Smith41956372013-01-14 22:39:08 +00002680 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002681 // The initialization of each base and member constitutes a
2682 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002683 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2684 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002685 if (DelegationInit.isInvalid())
2686 return true;
2687
Eli Friedmand21016f2012-05-19 23:35:23 +00002688 // If we are in a dependent context, template instantiation will
2689 // perform this type-checking again. Just save the arguments that we
2690 // received in a ParenListExpr.
2691 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2692 // of the information that we have about the base
2693 // initializer. However, deconstructing the ASTs is a dicey process,
2694 // and this approach is far more likely to get the corner cases right.
2695 if (CurContext->isDependentContext())
2696 DelegationInit = Owned(Init);
2697
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002698 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002699 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002700 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002701}
2702
2703MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002704Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002705 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002706 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002707 SourceLocation BaseLoc
2708 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002709
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002710 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2711 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2712 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2713
2714 // C++ [class.base.init]p2:
2715 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002716 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002717 // of that class, the mem-initializer is ill-formed. A
2718 // mem-initializer-list can initialize a base class using any
2719 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002720 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002721
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002722 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002723 if (EllipsisLoc.isValid()) {
2724 // This is a pack expansion.
2725 if (!BaseType->containsUnexpandedParameterPack()) {
2726 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002727 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002728
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002729 EllipsisLoc = SourceLocation();
2730 }
2731 } else {
2732 // Check for any unexpanded parameter packs.
2733 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2734 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002735
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002736 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002737 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002738 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002739
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002740 // Check for direct and virtual base classes.
2741 const CXXBaseSpecifier *DirectBaseSpec = 0;
2742 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2743 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002744 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2745 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002746 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002747
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002748 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2749 VirtualBaseSpec);
2750
2751 // C++ [base.class.init]p2:
2752 // Unless the mem-initializer-id names a nonstatic data member of the
2753 // constructor's class or a direct or virtual base of that class, the
2754 // mem-initializer is ill-formed.
2755 if (!DirectBaseSpec && !VirtualBaseSpec) {
2756 // If the class has any dependent bases, then it's possible that
2757 // one of those types will resolve to the same type as
2758 // BaseType. Therefore, just treat this as a dependent base
2759 // class initialization. FIXME: Should we try to check the
2760 // initialization anyway? It seems odd.
2761 if (ClassDecl->hasAnyDependentBases())
2762 Dependent = true;
2763 else
2764 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2765 << BaseType << Context.getTypeDeclType(ClassDecl)
2766 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2767 }
2768 }
2769
2770 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002771 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Sebastian Redl6df65482011-09-24 17:48:25 +00002773 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2774 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002775 InitRange.getBegin(), Init,
2776 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002777 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002778
2779 // C++ [base.class.init]p2:
2780 // If a mem-initializer-id is ambiguous because it designates both
2781 // a direct non-virtual base class and an inherited virtual base
2782 // class, the mem-initializer is ill-formed.
2783 if (DirectBaseSpec && VirtualBaseSpec)
2784 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002785 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002786
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002787 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002788 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002789 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002790
2791 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002792 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002793 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002794 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002795 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002796 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002797 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002798
2799 InitializedEntity BaseEntity =
2800 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2801 InitializationKind Kind =
2802 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2803 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2804 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002805 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2806 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002807 if (BaseInit.isInvalid())
2808 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002809
Richard Smith41956372013-01-14 22:39:08 +00002810 // C++11 [class.base.init]p7:
2811 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002812 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002813 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002814 if (BaseInit.isInvalid())
2815 return true;
2816
2817 // If we are in a dependent context, template instantiation will
2818 // perform this type-checking again. Just save the arguments that we
2819 // received in a ParenListExpr.
2820 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2821 // of the information that we have about the base
2822 // initializer. However, deconstructing the ASTs is a dicey process,
2823 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002824 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002825 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002826
Sean Huntcbb67482011-01-08 20:30:50 +00002827 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002828 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002829 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002830 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002831 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002832}
2833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002834// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002835static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2836 if (T.isNull()) T = E->getType();
2837 QualType TargetType = SemaRef.BuildReferenceType(
2838 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002839 SourceLocation ExprLoc = E->getLocStart();
2840 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2841 TargetType, ExprLoc);
2842
2843 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2844 SourceRange(ExprLoc, ExprLoc),
2845 E->getSourceRange()).take();
2846}
2847
Anders Carlssone5ef7402010-04-23 03:10:23 +00002848/// ImplicitInitializerKind - How an implicit base or member initializer should
2849/// initialize its base or member.
2850enum ImplicitInitializerKind {
2851 IIK_Default,
2852 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002853 IIK_Move,
2854 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002855};
2856
Anders Carlssondefefd22010-04-23 02:00:02 +00002857static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002858BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002859 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002860 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002861 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002862 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002863 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002864 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2865 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002866
John McCall60d7b3a2010-08-24 06:29:42 +00002867 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002868
2869 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002870 case IIK_Inherit: {
2871 const CXXRecordDecl *Inherited =
2872 Constructor->getInheritedConstructor()->getParent();
2873 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2874 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2875 // C++11 [class.inhctor]p8:
2876 // Each expression in the expression-list is of the form
2877 // static_cast<T&&>(p), where p is the name of the corresponding
2878 // constructor parameter and T is the declared type of p.
2879 SmallVector<Expr*, 16> Args;
2880 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2881 ParmVarDecl *PD = Constructor->getParamDecl(I);
2882 ExprResult ArgExpr =
2883 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2884 VK_LValue, SourceLocation());
2885 if (ArgExpr.isInvalid())
2886 return true;
2887 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2888 }
2889
2890 InitializationKind InitKind = InitializationKind::CreateDirect(
2891 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002892 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002893 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2894 break;
2895 }
2896 }
2897 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002898 case IIK_Default: {
2899 InitializationKind InitKind
2900 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002901 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2902 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002903 break;
2904 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002905
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002906 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002907 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002908 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002909 ParmVarDecl *Param = Constructor->getParamDecl(0);
2910 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002911
Anders Carlssone5ef7402010-04-23 03:10:23 +00002912 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002913 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002914 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002915 Constructor->getLocation(), ParamType,
2916 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002917
Eli Friedman5f2987c2012-02-02 03:46:19 +00002918 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2919
Anders Carlssonc7957502010-04-24 22:02:54 +00002920 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002921 QualType ArgTy =
2922 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2923 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002924
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002925 if (Moving) {
2926 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2927 }
2928
John McCallf871d0c2010-08-07 06:22:56 +00002929 CXXCastPath BasePath;
2930 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002931 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2932 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002933 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002934 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002935
Anders Carlssone5ef7402010-04-23 03:10:23 +00002936 InitializationKind InitKind
2937 = InitializationKind::CreateDirect(Constructor->getLocation(),
2938 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002939 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2940 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002941 break;
2942 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002943 }
John McCall9ae2f072010-08-23 23:25:46 +00002944
Douglas Gregor53c374f2010-12-07 00:41:46 +00002945 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002946 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002947 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002948
Anders Carlssondefefd22010-04-23 02:00:02 +00002949 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002950 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002951 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2952 SourceLocation()),
2953 BaseSpec->isVirtual(),
2954 SourceLocation(),
2955 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002956 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002957 SourceLocation());
2958
Anders Carlssondefefd22010-04-23 02:00:02 +00002959 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002960}
2961
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002962static bool RefersToRValueRef(Expr *MemRef) {
2963 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2964 return Referenced->getType()->isRValueReferenceType();
2965}
2966
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002967static bool
2968BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002969 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002970 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002971 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002972 if (Field->isInvalidDecl())
2973 return true;
2974
Chandler Carruthf186b542010-06-29 23:50:44 +00002975 SourceLocation Loc = Constructor->getLocation();
2976
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002977 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2978 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002979 ParmVarDecl *Param = Constructor->getParamDecl(0);
2980 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002981
2982 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002983 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2984 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002985
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002986 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002987 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002988 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002989 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002990
Eli Friedman5f2987c2012-02-02 03:46:19 +00002991 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2992
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002993 if (Moving) {
2994 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2995 }
2996
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002997 // Build a reference to this field within the parameter.
2998 CXXScopeSpec SS;
2999 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3000 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003001 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3002 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003003 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003004 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003005 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003006 ParamType, Loc,
3007 /*IsArrow=*/false,
3008 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003009 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003010 /*FirstQualifierInScope=*/0,
3011 MemberLookup,
3012 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003013 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003014 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003015
3016 // C++11 [class.copy]p15:
3017 // - if a member m has rvalue reference type T&&, it is direct-initialized
3018 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003019 if (RefersToRValueRef(CtorArg.get())) {
3020 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003021 }
3022
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003023 // When the field we are copying is an array, create index variables for
3024 // each dimension of the array. We use these index variables to subscript
3025 // the source array, and other clients (e.g., CodeGen) will perform the
3026 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003027 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003028 QualType BaseType = Field->getType();
3029 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003030 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003031 while (const ConstantArrayType *Array
3032 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003033 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003034 // Create the iteration variable for this array index.
3035 IdentifierInfo *IterationVarName = 0;
3036 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003037 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003038 llvm::raw_svector_ostream OS(Str);
3039 OS << "__i" << IndexVariables.size();
3040 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3041 }
3042 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003043 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003044 IterationVarName, SizeType,
3045 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003046 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003047 IndexVariables.push_back(IterationVar);
3048
3049 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003050 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003051 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003052 assert(!IterationVarRef.isInvalid() &&
3053 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003054 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3055 assert(!IterationVarRef.isInvalid() &&
3056 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003057
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003058 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003059 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003060 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003061 Loc);
3062 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003063 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003064
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003065 BaseType = Array->getElementType();
3066 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003067
3068 // The array subscript expression is an lvalue, which is wrong for moving.
3069 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003070 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003071
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003072 // Construct the entity that we will be initializing. For an array, this
3073 // will be first element in the array, which may require several levels
3074 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003075 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003076 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003077 if (Indirect)
3078 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3079 else
3080 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003081 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3082 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3083 0,
3084 Entities.back()));
3085
3086 // Direct-initialize to use the copy constructor.
3087 InitializationKind InitKind =
3088 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3089
Sebastian Redl74e611a2011-09-04 18:14:28 +00003090 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003091 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003092
John McCall60d7b3a2010-08-24 06:29:42 +00003093 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003094 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003095 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003096 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003097 if (MemberInit.isInvalid())
3098 return true;
3099
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003100 if (Indirect) {
3101 assert(IndexVariables.size() == 0 &&
3102 "Indirect field improperly initialized");
3103 CXXMemberInit
3104 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3105 Loc, Loc,
3106 MemberInit.takeAs<Expr>(),
3107 Loc);
3108 } else
3109 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3110 Loc, MemberInit.takeAs<Expr>(),
3111 Loc,
3112 IndexVariables.data(),
3113 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003114 return false;
3115 }
3116
Richard Smith07b0fdc2013-03-18 21:12:30 +00003117 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3118 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003119
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003120 QualType FieldBaseElementType =
3121 SemaRef.Context.getBaseElementType(Field->getType());
3122
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003123 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003124 InitializedEntity InitEntity
3125 = Indirect? InitializedEntity::InitializeMember(Indirect)
3126 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003127 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003128 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003129
3130 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3131 ExprResult MemberInit =
3132 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003133
Douglas Gregor53c374f2010-12-07 00:41:46 +00003134 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003135 if (MemberInit.isInvalid())
3136 return true;
3137
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003138 if (Indirect)
3139 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3140 Indirect, Loc,
3141 Loc,
3142 MemberInit.get(),
3143 Loc);
3144 else
3145 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3146 Field, Loc, Loc,
3147 MemberInit.get(),
3148 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003149 return false;
3150 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003151
Sean Hunt1f2f3842011-05-17 00:19:05 +00003152 if (!Field->getParent()->isUnion()) {
3153 if (FieldBaseElementType->isReferenceType()) {
3154 SemaRef.Diag(Constructor->getLocation(),
3155 diag::err_uninitialized_member_in_ctor)
3156 << (int)Constructor->isImplicit()
3157 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3158 << 0 << Field->getDeclName();
3159 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3160 return true;
3161 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003162
Sean Hunt1f2f3842011-05-17 00:19:05 +00003163 if (FieldBaseElementType.isConstQualified()) {
3164 SemaRef.Diag(Constructor->getLocation(),
3165 diag::err_uninitialized_member_in_ctor)
3166 << (int)Constructor->isImplicit()
3167 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3168 << 1 << Field->getDeclName();
3169 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3170 return true;
3171 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003172 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003173
David Blaikie4e4d0842012-03-11 07:00:24 +00003174 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003175 FieldBaseElementType->isObjCRetainableType() &&
3176 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3177 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003178 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003179 // Default-initialize Objective-C pointers to NULL.
3180 CXXMemberInit
3181 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3182 Loc, Loc,
3183 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3184 Loc);
3185 return false;
3186 }
3187
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003188 // Nothing to initialize.
3189 CXXMemberInit = 0;
3190 return false;
3191}
John McCallf1860e52010-05-20 23:23:51 +00003192
3193namespace {
3194struct BaseAndFieldInfo {
3195 Sema &S;
3196 CXXConstructorDecl *Ctor;
3197 bool AnyErrorsInInits;
3198 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003199 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003200 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003201
3202 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3203 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003204 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3205 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003206 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003207 else if (Generated && Ctor->isMoveConstructor())
3208 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003209 else if (Ctor->getInheritedConstructor())
3210 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003211 else
3212 IIK = IIK_Default;
3213 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003214
3215 bool isImplicitCopyOrMove() const {
3216 switch (IIK) {
3217 case IIK_Copy:
3218 case IIK_Move:
3219 return true;
3220
3221 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003222 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003223 return false;
3224 }
David Blaikie30263482012-01-20 21:50:17 +00003225
3226 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003227 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003228
3229 bool addFieldInitializer(CXXCtorInitializer *Init) {
3230 AllToInit.push_back(Init);
3231
3232 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003233 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003234 S.UnusedPrivateFields.remove(Init->getAnyMember());
3235
3236 return false;
3237 }
John McCallf1860e52010-05-20 23:23:51 +00003238};
3239}
3240
Richard Smitha4950662011-09-19 13:34:43 +00003241/// \brief Determine whether the given indirect field declaration is somewhere
3242/// within an anonymous union.
3243static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3244 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3245 CEnd = F->chain_end();
3246 C != CEnd; ++C)
3247 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3248 if (Record->isUnion())
3249 return true;
3250
3251 return false;
3252}
3253
Douglas Gregorddb21472011-11-02 23:04:16 +00003254/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3255/// array type.
3256static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3257 if (T->isIncompleteArrayType())
3258 return true;
3259
3260 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3261 if (!ArrayT->getSize())
3262 return true;
3263
3264 T = ArrayT->getElementType();
3265 }
3266
3267 return false;
3268}
3269
Richard Smith7a614d82011-06-11 17:19:42 +00003270static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003271 FieldDecl *Field,
3272 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003273 if (Field->isInvalidDecl())
3274 return false;
John McCallf1860e52010-05-20 23:23:51 +00003275
Chandler Carruthe861c602010-06-30 02:59:29 +00003276 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003277 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3278 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003279
Richard Smith0b8220a2012-08-07 21:30:42 +00003280 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003281 // has a brace-or-equal-initializer, the entity is initialized as specified
3282 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003283 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003284 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3285 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003286 CXXCtorInitializer *Init;
3287 if (Indirect)
3288 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3289 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003290 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003291 SourceLocation());
3292 else
3293 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3294 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003295 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003296 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003297 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003298 }
3299
Richard Smithc115f632011-09-18 11:14:50 +00003300 // Don't build an implicit initializer for union members if none was
3301 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003302 if (Field->getParent()->isUnion() ||
3303 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003304 return false;
3305
Douglas Gregorddb21472011-11-02 23:04:16 +00003306 // Don't initialize incomplete or zero-length arrays.
3307 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3308 return false;
3309
John McCallf1860e52010-05-20 23:23:51 +00003310 // Don't try to build an implicit initializer if there were semantic
3311 // errors in any of the initializers (and therefore we might be
3312 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003313 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003314 return false;
3315
Sean Huntcbb67482011-01-08 20:30:50 +00003316 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003317 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3318 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003319 return true;
John McCallf1860e52010-05-20 23:23:51 +00003320
Richard Smith0b8220a2012-08-07 21:30:42 +00003321 if (!Init)
3322 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003323
Richard Smith0b8220a2012-08-07 21:30:42 +00003324 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003325}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003326
3327bool
3328Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3329 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003330 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003331 Constructor->setNumCtorInitializers(1);
3332 CXXCtorInitializer **initializer =
3333 new (Context) CXXCtorInitializer*[1];
3334 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3335 Constructor->setCtorInitializers(initializer);
3336
Sean Huntb76af9c2011-05-03 23:05:34 +00003337 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003338 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003339 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3340 }
3341
Sean Huntc1598702011-05-05 00:05:47 +00003342 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003343
Sean Hunt059ce0d2011-05-01 07:04:31 +00003344 return false;
3345}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003346
David Blaikie93c86172013-01-17 05:26:25 +00003347bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3348 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003349 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003350 // Just store the initializers as written, they will be checked during
3351 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003352 if (!Initializers.empty()) {
3353 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003354 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003355 new (Context) CXXCtorInitializer*[Initializers.size()];
3356 memcpy(baseOrMemberInitializers, Initializers.data(),
3357 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003358 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003359 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003360
3361 // Let template instantiation know whether we had errors.
3362 if (AnyErrors)
3363 Constructor->setInvalidDecl();
3364
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003365 return false;
3366 }
3367
John McCallf1860e52010-05-20 23:23:51 +00003368 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003369
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003370 // We need to build the initializer AST according to order of construction
3371 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003372 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003373 if (!ClassDecl)
3374 return true;
3375
Eli Friedman80c30da2009-11-09 19:20:36 +00003376 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003377
David Blaikie93c86172013-01-17 05:26:25 +00003378 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003379 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003380
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003381 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003382 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003383 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003384 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003385 }
3386
Anders Carlsson711f34a2010-04-21 19:52:01 +00003387 // Keep track of the direct virtual bases.
3388 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3389 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3390 E = ClassDecl->bases_end(); I != E; ++I) {
3391 if (I->isVirtual())
3392 DirectVBases.insert(I);
3393 }
3394
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003395 // Push virtual bases before others.
3396 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3397 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3398
Sean Huntcbb67482011-01-08 20:30:50 +00003399 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003400 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003401 // [class.base.init]p7, per DR257:
3402 // A mem-initializer where the mem-initializer-id names a virtual base
3403 // class is ignored during execution of a constructor of any class that
3404 // is not the most derived class.
3405 if (ClassDecl->isAbstract()) {
3406 // FIXME: Provide a fixit to remove the base specifier. This requires
3407 // tracking the location of the associated comma for a base specifier.
3408 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3409 << VBase->getType() << ClassDecl;
3410 DiagnoseAbstractType(ClassDecl);
3411 }
3412
John McCallf1860e52010-05-20 23:23:51 +00003413 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003414 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3415 // [class.base.init]p8, per DR257:
3416 // If a given [...] base class is not named by a mem-initializer-id
3417 // [...] and the entity is not a virtual base class of an abstract
3418 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003419 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003420 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003421 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003422 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003423 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003424 HadError = true;
3425 continue;
3426 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003427
John McCallf1860e52010-05-20 23:23:51 +00003428 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003429 }
3430 }
Mike Stump1eb44332009-09-09 15:08:12 +00003431
John McCallf1860e52010-05-20 23:23:51 +00003432 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003433 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3434 E = ClassDecl->bases_end(); Base != E; ++Base) {
3435 // Virtuals are in the virtual base list and already constructed.
3436 if (Base->isVirtual())
3437 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Sean Huntcbb67482011-01-08 20:30:50 +00003439 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003440 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3441 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003442 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003443 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003444 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003445 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003446 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003447 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003448 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003449 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003450
John McCallf1860e52010-05-20 23:23:51 +00003451 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003452 }
3453 }
Mike Stump1eb44332009-09-09 15:08:12 +00003454
John McCallf1860e52010-05-20 23:23:51 +00003455 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003456 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3457 MemEnd = ClassDecl->decls_end();
3458 Mem != MemEnd; ++Mem) {
3459 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003460 // C++ [class.bit]p2:
3461 // A declaration for a bit-field that omits the identifier declares an
3462 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3463 // initialized.
3464 if (F->isUnnamedBitfield())
3465 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003466
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003467 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003468 // handle anonymous struct/union fields based on their individual
3469 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003470 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003471 continue;
3472
3473 if (CollectFieldInitializer(*this, Info, F))
3474 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003475 continue;
3476 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003477
3478 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003479 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003480 continue;
3481
3482 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3483 if (F->getType()->isIncompleteArrayType()) {
3484 assert(ClassDecl->hasFlexibleArrayMember() &&
3485 "Incomplete array type is not valid");
3486 continue;
3487 }
3488
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003489 // Initialize each field of an anonymous struct individually.
3490 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3491 HadError = true;
3492
3493 continue;
3494 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003495 }
Mike Stump1eb44332009-09-09 15:08:12 +00003496
David Blaikie93c86172013-01-17 05:26:25 +00003497 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003498 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003499 Constructor->setNumCtorInitializers(NumInitializers);
3500 CXXCtorInitializer **baseOrMemberInitializers =
3501 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003502 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003503 NumInitializers * sizeof(CXXCtorInitializer*));
3504 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003505
John McCallef027fe2010-03-16 21:39:52 +00003506 // Constructors implicitly reference the base and member
3507 // destructors.
3508 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3509 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003510 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003511
3512 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003513}
3514
David Blaikieee000bb2013-01-17 08:49:22 +00003515static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003516 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003517 const RecordDecl *RD = RT->getDecl();
3518 if (RD->isAnonymousStructOrUnion()) {
3519 for (RecordDecl::field_iterator Field = RD->field_begin(),
3520 E = RD->field_end(); Field != E; ++Field)
3521 PopulateKeysForFields(*Field, IdealInits);
3522 return;
3523 }
Eli Friedman6347f422009-07-21 19:28:10 +00003524 }
David Blaikieee000bb2013-01-17 08:49:22 +00003525 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003526}
3527
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003528static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3529 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003530}
3531
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003532static const void *GetKeyForMember(ASTContext &Context,
3533 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003534 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003535 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003536
David Blaikieee000bb2013-01-17 08:49:22 +00003537 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003538}
3539
David Blaikie93c86172013-01-17 05:26:25 +00003540static void DiagnoseBaseOrMemInitializerOrder(
3541 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3542 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003543 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003544 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003546 // Don't check initializers order unless the warning is enabled at the
3547 // location of at least one initializer.
3548 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003549 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003550 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003551 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3552 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003553 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003554 ShouldCheckOrder = true;
3555 break;
3556 }
3557 }
3558 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003559 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003560
John McCalld6ca8da2010-04-10 07:37:23 +00003561 // Build the list of bases and members in the order that they'll
3562 // actually be initialized. The explicit initializers should be in
3563 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003564 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Anders Carlsson071d6102010-04-02 03:38:04 +00003566 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3567
John McCalld6ca8da2010-04-10 07:37:23 +00003568 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003569 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003570 ClassDecl->vbases_begin(),
3571 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003572 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003573
John McCalld6ca8da2010-04-10 07:37:23 +00003574 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003575 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003576 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003577 if (Base->isVirtual())
3578 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003579 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003580 }
Mike Stump1eb44332009-09-09 15:08:12 +00003581
John McCalld6ca8da2010-04-10 07:37:23 +00003582 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003583 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003584 E = ClassDecl->field_end(); Field != E; ++Field) {
3585 if (Field->isUnnamedBitfield())
3586 continue;
3587
David Blaikieee000bb2013-01-17 08:49:22 +00003588 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003589 }
3590
John McCalld6ca8da2010-04-10 07:37:23 +00003591 unsigned NumIdealInits = IdealInitKeys.size();
3592 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003593
Sean Huntcbb67482011-01-08 20:30:50 +00003594 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003595 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003596 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003597 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003598
3599 // Scan forward to try to find this initializer in the idealized
3600 // initializers list.
3601 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3602 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003603 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003604
3605 // If we didn't find this initializer, it must be because we
3606 // scanned past it on a previous iteration. That can only
3607 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003608 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003609 Sema::SemaDiagnosticBuilder D =
3610 SemaRef.Diag(PrevInit->getSourceLocation(),
3611 diag::warn_initializer_out_of_order);
3612
Francois Pichet00eb3f92010-12-04 09:14:42 +00003613 if (PrevInit->isAnyMemberInitializer())
3614 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003615 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003616 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003617
Francois Pichet00eb3f92010-12-04 09:14:42 +00003618 if (Init->isAnyMemberInitializer())
3619 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003620 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003621 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003622
3623 // Move back to the initializer's location in the ideal list.
3624 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3625 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003626 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003627
3628 assert(IdealIndex != NumIdealInits &&
3629 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003630 }
John McCalld6ca8da2010-04-10 07:37:23 +00003631
3632 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003633 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003634}
3635
John McCall3c3ccdb2010-04-10 09:28:51 +00003636namespace {
3637bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003638 CXXCtorInitializer *Init,
3639 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003640 if (!PrevInit) {
3641 PrevInit = Init;
3642 return false;
3643 }
3644
Douglas Gregordc392c12013-03-25 23:28:23 +00003645 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003646 S.Diag(Init->getSourceLocation(),
3647 diag::err_multiple_mem_initialization)
3648 << Field->getDeclName()
3649 << Init->getSourceRange();
3650 else {
John McCallf4c73712011-01-19 06:33:43 +00003651 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003652 assert(BaseClass && "neither field nor base");
3653 S.Diag(Init->getSourceLocation(),
3654 diag::err_multiple_base_initialization)
3655 << QualType(BaseClass, 0)
3656 << Init->getSourceRange();
3657 }
3658 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3659 << 0 << PrevInit->getSourceRange();
3660
3661 return true;
3662}
3663
Sean Huntcbb67482011-01-08 20:30:50 +00003664typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003665typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3666
3667bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003668 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003669 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003670 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003671 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003672 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003673
3674 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003675 if (Parent->isUnion()) {
3676 UnionEntry &En = Unions[Parent];
3677 if (En.first && En.first != Child) {
3678 S.Diag(Init->getSourceLocation(),
3679 diag::err_multiple_mem_union_initialization)
3680 << Field->getDeclName()
3681 << Init->getSourceRange();
3682 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3683 << 0 << En.second->getSourceRange();
3684 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003685 }
3686 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003687 En.first = Child;
3688 En.second = Init;
3689 }
David Blaikie6fe29652011-11-17 06:01:57 +00003690 if (!Parent->isAnonymousStructOrUnion())
3691 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003692 }
3693
3694 Child = Parent;
3695 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003696 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003697
3698 return false;
3699}
3700}
3701
Richard Trieu225e9822013-09-16 21:54:53 +00003702// Diagnose value-uses of fields to initialize themselves, e.g.
3703// foo(foo)
3704// where foo is not also a parameter to the constructor.
3705// TODO: implement -Wuninitialized and fold this into that framework.
3706// FIXME: Warn about the case when other fields are used before being
3707// initialized. For example, let this field be the i'th field. When
3708// initializing the i'th field, throw a warning if any of the >= i'th
3709// fields are used, as they are not yet initialized.
3710// Right now we are only handling the case where the i'th field uses
3711// itself in its initializer.
3712// Also need to take into account that some fields may be initialized by
3713// in-class initializers, see C++11 [class.base.init]p9.
3714static void DiagnoseUnitializedFields(
3715 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3716
3717 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
3718 Constructor->getLocation())
3719 == DiagnosticsEngine::Ignored) {
3720 return;
3721 }
3722
3723 for (CXXConstructorDecl::init_const_iterator
3724 FieldInit = Constructor->init_begin(),
3725 FieldInitEnd = Constructor->init_end();
3726 FieldInit != FieldInitEnd; ++FieldInit) {
3727
3728 FieldDecl *FD = (*FieldInit)->getAnyMember();
3729 if (!FD)
3730 continue;
3731 Expr *InitExpr = (*FieldInit)->getInit();
3732
3733 if (!isa<CXXDefaultInitExpr>(InitExpr)) {
3734 CheckInitExprContainsUninitializedFields(SemaRef, InitExpr, FD);
3735 }
3736 }
3737}
3738
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003739/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003740void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003741 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003742 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003743 bool AnyErrors) {
3744 if (!ConstructorDecl)
3745 return;
3746
3747 AdjustDeclIfTemplate(ConstructorDecl);
3748
3749 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003750 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003751
3752 if (!Constructor) {
3753 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3754 return;
3755 }
3756
John McCall3c3ccdb2010-04-10 09:28:51 +00003757 // Mapping for the duplicate initializers check.
3758 // For member initializers, this is keyed with a FieldDecl*.
3759 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003760 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003761
3762 // Mapping for the inconsistent anonymous-union initializers check.
3763 RedundantUnionMap MemberUnions;
3764
Anders Carlssonea356fb2010-04-02 05:42:15 +00003765 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003766 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003767 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003768
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003769 // Set the source order index.
3770 Init->setSourceOrder(i);
3771
Francois Pichet00eb3f92010-12-04 09:14:42 +00003772 if (Init->isAnyMemberInitializer()) {
3773 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003774 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3775 CheckRedundantUnionInit(*this, Init, MemberUnions))
3776 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003777 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003778 const void *Key =
3779 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003780 if (CheckRedundantInit(*this, Init, Members[Key]))
3781 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003782 } else {
3783 assert(Init->isDelegatingInitializer());
3784 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003785 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003786 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003787 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003788 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003789 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003790 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003791 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003792 // Return immediately as the initializer is set.
3793 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003794 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003795 }
3796
Anders Carlssonea356fb2010-04-02 05:42:15 +00003797 if (HadError)
3798 return;
3799
David Blaikie93c86172013-01-17 05:26:25 +00003800 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003801
David Blaikie93c86172013-01-17 05:26:25 +00003802 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003803
3804 DiagnoseUnitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003805}
3806
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003807void
John McCallef027fe2010-03-16 21:39:52 +00003808Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3809 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003810 // Ignore dependent contexts. Also ignore unions, since their members never
3811 // have destructors implicitly called.
3812 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003813 return;
John McCall58e6f342010-03-16 05:22:47 +00003814
3815 // FIXME: all the access-control diagnostics are positioned on the
3816 // field/base declaration. That's probably good; that said, the
3817 // user might reasonably want to know why the destructor is being
3818 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003819
Anders Carlsson9f853df2009-11-17 04:44:12 +00003820 // Non-static data members.
3821 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3822 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003823 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003824 if (Field->isInvalidDecl())
3825 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003826
3827 // Don't destroy incomplete or zero-length arrays.
3828 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3829 continue;
3830
Anders Carlsson9f853df2009-11-17 04:44:12 +00003831 QualType FieldType = Context.getBaseElementType(Field->getType());
3832
3833 const RecordType* RT = FieldType->getAs<RecordType>();
3834 if (!RT)
3835 continue;
3836
3837 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003838 if (FieldClassDecl->isInvalidDecl())
3839 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003840 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003841 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003842 // The destructor for an implicit anonymous union member is never invoked.
3843 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3844 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003845
Douglas Gregordb89f282010-07-01 22:47:18 +00003846 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003847 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003848 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003849 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003850 << Field->getDeclName()
3851 << FieldType);
3852
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003853 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003854 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003855 }
3856
John McCall58e6f342010-03-16 05:22:47 +00003857 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3858
Anders Carlsson9f853df2009-11-17 04:44:12 +00003859 // Bases.
3860 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3861 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003862 // Bases are always records in a well-formed non-dependent class.
3863 const RecordType *RT = Base->getType()->getAs<RecordType>();
3864
3865 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003866 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003867 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003868
John McCall58e6f342010-03-16 05:22:47 +00003869 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003870 // If our base class is invalid, we probably can't get its dtor anyway.
3871 if (BaseClassDecl->isInvalidDecl())
3872 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003873 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003874 continue;
John McCall58e6f342010-03-16 05:22:47 +00003875
Douglas Gregordb89f282010-07-01 22:47:18 +00003876 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003877 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003878
3879 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003880 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003881 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003882 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003883 << Base->getSourceRange(),
3884 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003885
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003886 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003887 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003888 }
3889
3890 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003891 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3892 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003893
3894 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003895 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003896
3897 // Ignore direct virtual bases.
3898 if (DirectVirtualBases.count(RT))
3899 continue;
3900
John McCall58e6f342010-03-16 05:22:47 +00003901 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003902 // If our base class is invalid, we probably can't get its dtor anyway.
3903 if (BaseClassDecl->isInvalidDecl())
3904 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003905 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003906 continue;
John McCall58e6f342010-03-16 05:22:47 +00003907
Douglas Gregordb89f282010-07-01 22:47:18 +00003908 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003909 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003910 if (CheckDestructorAccess(
3911 ClassDecl->getLocation(), Dtor,
3912 PDiag(diag::err_access_dtor_vbase)
3913 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3914 Context.getTypeDeclType(ClassDecl)) ==
3915 AR_accessible) {
3916 CheckDerivedToBaseConversion(
3917 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3918 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3919 SourceRange(), DeclarationName(), 0);
3920 }
John McCall58e6f342010-03-16 05:22:47 +00003921
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003922 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003923 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003924 }
3925}
3926
John McCalld226f652010-08-21 09:40:31 +00003927void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003928 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003929 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Mike Stump1eb44332009-09-09 15:08:12 +00003931 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003932 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003933 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003934}
3935
Mike Stump1eb44332009-09-09 15:08:12 +00003936bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003937 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003938 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3939 unsigned DiagID;
3940 AbstractDiagSelID SelID;
3941
3942 public:
3943 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3944 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003945
3946 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00003947 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003948 if (SelID == -1)
3949 S.Diag(Loc, DiagID) << T;
3950 else
3951 S.Diag(Loc, DiagID) << SelID << T;
3952 }
3953 } Diagnoser(DiagID, SelID);
3954
3955 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003956}
3957
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003958bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003959 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003960 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003961 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Anders Carlsson11f21a02009-03-23 19:10:31 +00003963 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003964 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Ted Kremenek6217b802009-07-29 21:53:49 +00003966 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003967 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003968 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003969 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003970
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003971 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003972 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003973 }
Mike Stump1eb44332009-09-09 15:08:12 +00003974
Ted Kremenek6217b802009-07-29 21:53:49 +00003975 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003976 if (!RT)
3977 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003978
John McCall86ff3082010-02-04 22:26:26 +00003979 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003980
John McCall94c3b562010-08-18 09:41:07 +00003981 // We can't answer whether something is abstract until it has a
3982 // definition. If it's currently being defined, we'll walk back
3983 // over all the declarations when we have a full definition.
3984 const CXXRecordDecl *Def = RD->getDefinition();
3985 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003986 return false;
3987
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003988 if (!RD->isAbstract())
3989 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003991 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003992 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003993
John McCall94c3b562010-08-18 09:41:07 +00003994 return true;
3995}
3996
3997void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3998 // Check if we've already emitted the list of pure virtual functions
3999 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004000 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004001 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004002
Richard Smithcbc820a2013-07-22 02:56:56 +00004003 // If the diagnostic is suppressed, don't emit the notes. We're only
4004 // going to emit them once, so try to attach them to a diagnostic we're
4005 // actually going to show.
4006 if (Diags.isLastDiagnosticIgnored())
4007 return;
4008
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004009 CXXFinalOverriderMap FinalOverriders;
4010 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004012 // Keep a set of seen pure methods so we won't diagnose the same method
4013 // more than once.
4014 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4015
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004016 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4017 MEnd = FinalOverriders.end();
4018 M != MEnd;
4019 ++M) {
4020 for (OverridingMethods::iterator SO = M->second.begin(),
4021 SOEnd = M->second.end();
4022 SO != SOEnd; ++SO) {
4023 // C++ [class.abstract]p4:
4024 // A class is abstract if it contains or inherits at least one
4025 // pure virtual function for which the final overrider is pure
4026 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004027
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004028 //
4029 if (SO->second.size() != 1)
4030 continue;
4031
4032 if (!SO->second.front().Method->isPure())
4033 continue;
4034
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004035 if (!SeenPureMethods.insert(SO->second.front().Method))
4036 continue;
4037
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004038 Diag(SO->second.front().Method->getLocation(),
4039 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004040 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004041 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004042 }
4043
4044 if (!PureVirtualClassDiagSet)
4045 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4046 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004047}
4048
Anders Carlsson8211eff2009-03-24 01:19:16 +00004049namespace {
John McCall94c3b562010-08-18 09:41:07 +00004050struct AbstractUsageInfo {
4051 Sema &S;
4052 CXXRecordDecl *Record;
4053 CanQualType AbstractType;
4054 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004055
John McCall94c3b562010-08-18 09:41:07 +00004056 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4057 : S(S), Record(Record),
4058 AbstractType(S.Context.getCanonicalType(
4059 S.Context.getTypeDeclType(Record))),
4060 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004061
John McCall94c3b562010-08-18 09:41:07 +00004062 void DiagnoseAbstractType() {
4063 if (Invalid) return;
4064 S.DiagnoseAbstractType(Record);
4065 Invalid = true;
4066 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004067
John McCall94c3b562010-08-18 09:41:07 +00004068 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4069};
4070
4071struct CheckAbstractUsage {
4072 AbstractUsageInfo &Info;
4073 const NamedDecl *Ctx;
4074
4075 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4076 : Info(Info), Ctx(Ctx) {}
4077
4078 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4079 switch (TL.getTypeLocClass()) {
4080#define ABSTRACT_TYPELOC(CLASS, PARENT)
4081#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004082 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004083#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004084 }
John McCall94c3b562010-08-18 09:41:07 +00004085 }
Mike Stump1eb44332009-09-09 15:08:12 +00004086
John McCall94c3b562010-08-18 09:41:07 +00004087 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4088 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4089 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004090 if (!TL.getArg(I))
4091 continue;
4092
John McCall94c3b562010-08-18 09:41:07 +00004093 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4094 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004095 }
John McCall94c3b562010-08-18 09:41:07 +00004096 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004097
John McCall94c3b562010-08-18 09:41:07 +00004098 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4099 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4100 }
Mike Stump1eb44332009-09-09 15:08:12 +00004101
John McCall94c3b562010-08-18 09:41:07 +00004102 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4103 // Visit the type parameters from a permissive context.
4104 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4105 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4106 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4107 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4108 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4109 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004110 }
John McCall94c3b562010-08-18 09:41:07 +00004111 }
Mike Stump1eb44332009-09-09 15:08:12 +00004112
John McCall94c3b562010-08-18 09:41:07 +00004113 // Visit pointee types from a permissive context.
4114#define CheckPolymorphic(Type) \
4115 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4116 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4117 }
4118 CheckPolymorphic(PointerTypeLoc)
4119 CheckPolymorphic(ReferenceTypeLoc)
4120 CheckPolymorphic(MemberPointerTypeLoc)
4121 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004122 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004123
John McCall94c3b562010-08-18 09:41:07 +00004124 /// Handle all the types we haven't given a more specific
4125 /// implementation for above.
4126 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4127 // Every other kind of type that we haven't called out already
4128 // that has an inner type is either (1) sugar or (2) contains that
4129 // inner type in some way as a subobject.
4130 if (TypeLoc Next = TL.getNextTypeLoc())
4131 return Visit(Next, Sel);
4132
4133 // If there's no inner type and we're in a permissive context,
4134 // don't diagnose.
4135 if (Sel == Sema::AbstractNone) return;
4136
4137 // Check whether the type matches the abstract type.
4138 QualType T = TL.getType();
4139 if (T->isArrayType()) {
4140 Sel = Sema::AbstractArrayType;
4141 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004142 }
John McCall94c3b562010-08-18 09:41:07 +00004143 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4144 if (CT != Info.AbstractType) return;
4145
4146 // It matched; do some magic.
4147 if (Sel == Sema::AbstractArrayType) {
4148 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4149 << T << TL.getSourceRange();
4150 } else {
4151 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4152 << Sel << T << TL.getSourceRange();
4153 }
4154 Info.DiagnoseAbstractType();
4155 }
4156};
4157
4158void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4159 Sema::AbstractDiagSelID Sel) {
4160 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4161}
4162
4163}
4164
4165/// Check for invalid uses of an abstract type in a method declaration.
4166static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4167 CXXMethodDecl *MD) {
4168 // No need to do the check on definitions, which require that
4169 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004170 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004171 return;
4172
4173 // For safety's sake, just ignore it if we don't have type source
4174 // information. This should never happen for non-implicit methods,
4175 // but...
4176 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4177 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4178}
4179
4180/// Check for invalid uses of an abstract type within a class definition.
4181static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4182 CXXRecordDecl *RD) {
4183 for (CXXRecordDecl::decl_iterator
4184 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4185 Decl *D = *I;
4186 if (D->isImplicit()) continue;
4187
4188 // Methods and method templates.
4189 if (isa<CXXMethodDecl>(D)) {
4190 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4191 } else if (isa<FunctionTemplateDecl>(D)) {
4192 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4193 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4194
4195 // Fields and static variables.
4196 } else if (isa<FieldDecl>(D)) {
4197 FieldDecl *FD = cast<FieldDecl>(D);
4198 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4199 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4200 } else if (isa<VarDecl>(D)) {
4201 VarDecl *VD = cast<VarDecl>(D);
4202 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4203 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4204
4205 // Nested classes and class templates.
4206 } else if (isa<CXXRecordDecl>(D)) {
4207 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4208 } else if (isa<ClassTemplateDecl>(D)) {
4209 CheckAbstractClassUsage(Info,
4210 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4211 }
4212 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004213}
4214
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004215/// \brief Perform semantic checks on a class definition that has been
4216/// completing, introducing implicitly-declared members, checking for
4217/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004218void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004219 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004220 return;
4221
John McCall94c3b562010-08-18 09:41:07 +00004222 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4223 AbstractUsageInfo Info(*this, Record);
4224 CheckAbstractClassUsage(Info, Record);
4225 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004226
4227 // If this is not an aggregate type and has no user-declared constructor,
4228 // complain about any non-static data members of reference or const scalar
4229 // type, since they will never get initializers.
4230 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004231 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4232 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004233 bool Complained = false;
4234 for (RecordDecl::field_iterator F = Record->field_begin(),
4235 FEnd = Record->field_end();
4236 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004237 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004238 continue;
4239
Douglas Gregor325e5932010-04-15 00:00:53 +00004240 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004241 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004242 if (!Complained) {
4243 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4244 << Record->getTagKind() << Record;
4245 Complained = true;
4246 }
4247
4248 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4249 << F->getType()->isReferenceType()
4250 << F->getDeclName();
4251 }
4252 }
4253 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004254
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004255 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004256 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004257
4258 if (Record->getIdentifier()) {
4259 // C++ [class.mem]p13:
4260 // If T is the name of a class, then each of the following shall have a
4261 // name different from T:
4262 // - every member of every anonymous union that is a member of class T.
4263 //
4264 // C++ [class.mem]p14:
4265 // In addition, if class T has a user-declared constructor (12.1), every
4266 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004267 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4268 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4269 ++I) {
4270 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004271 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4272 isa<IndirectFieldDecl>(D)) {
4273 Diag(D->getLocation(), diag::err_member_name_of_class)
4274 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004275 break;
4276 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004277 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004278 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004279
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004280 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004281 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004282 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004283 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004284 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4285 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4286 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004287
David Blaikieb6b5b972012-09-21 03:21:07 +00004288 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4289 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4290 DiagnoseAbstractType(Record);
4291 }
4292
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004293 if (!Record->isDependentType()) {
4294 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4295 MEnd = Record->method_end();
4296 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004297 // See if a method overloads virtual methods in a base
4298 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004299 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004300 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004301
4302 // Check whether the explicitly-defaulted special members are valid.
4303 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4304 CheckExplicitlyDefaultedSpecialMember(*M);
4305
4306 // For an explicitly defaulted or deleted special member, we defer
4307 // determining triviality until the class is complete. That time is now!
4308 if (!M->isImplicit() && !M->isUserProvided()) {
4309 CXXSpecialMember CSM = getSpecialMember(*M);
4310 if (CSM != CXXInvalid) {
4311 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4312
4313 // Inform the class that we've finished declaring this member.
4314 Record->finishedDefaultedOrDeletedMember(*M);
4315 }
4316 }
4317 }
4318 }
4319
4320 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4321 // function that is not a constructor declares that member function to be
4322 // const. [...] The class of which that function is a member shall be
4323 // a literal type.
4324 //
4325 // If the class has virtual bases, any constexpr members will already have
4326 // been diagnosed by the checks performed on the member declaration, so
4327 // suppress this (less useful) diagnostic.
4328 //
4329 // We delay this until we know whether an explicitly-defaulted (or deleted)
4330 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004331 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004332 !Record->isLiteral() && !Record->getNumVBases()) {
4333 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4334 MEnd = Record->method_end();
4335 M != MEnd; ++M) {
4336 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4337 switch (Record->getTemplateSpecializationKind()) {
4338 case TSK_ImplicitInstantiation:
4339 case TSK_ExplicitInstantiationDeclaration:
4340 case TSK_ExplicitInstantiationDefinition:
4341 // If a template instantiates to a non-literal type, but its members
4342 // instantiate to constexpr functions, the template is technically
4343 // ill-formed, but we allow it for sanity.
4344 continue;
4345
4346 case TSK_Undeclared:
4347 case TSK_ExplicitSpecialization:
4348 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4349 diag::err_constexpr_method_non_literal);
4350 break;
4351 }
4352
4353 // Only produce one error per class.
4354 break;
4355 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004356 }
4357 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004358
Richard Smith07b0fdc2013-03-18 21:12:30 +00004359 // Declare inheriting constructors. We do this eagerly here because:
4360 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004361 // constructors from different classes.
4362 // - The lazy declaration of the other implicit constructors is so as to not
4363 // waste space and performance on classes that are not meant to be
4364 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004365 // have inheriting constructors.
4366 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004367}
4368
Richard Smith7756afa2012-06-10 05:43:50 +00004369/// Is the special member function which would be selected to perform the
4370/// specified operation on the specified class type a constexpr constructor?
4371static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4372 Sema::CXXSpecialMember CSM,
4373 bool ConstArg) {
4374 Sema::SpecialMemberOverloadResult *SMOR =
4375 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4376 false, false, false, false);
4377 if (!SMOR || !SMOR->getMethod())
4378 // A constructor we wouldn't select can't be "involved in initializing"
4379 // anything.
4380 return true;
4381 return SMOR->getMethod()->isConstexpr();
4382}
4383
4384/// Determine whether the specified special member function would be constexpr
4385/// if it were implicitly defined.
4386static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4387 Sema::CXXSpecialMember CSM,
4388 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004389 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004390 return false;
4391
4392 // C++11 [dcl.constexpr]p4:
4393 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004394 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004395 switch (CSM) {
4396 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004397 // Since default constructor lookup is essentially trivial (and cannot
4398 // involve, for instance, template instantiation), we compute whether a
4399 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4400 //
4401 // This is important for performance; we need to know whether the default
4402 // constructor is constexpr to determine whether the type is a literal type.
4403 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4404
Richard Smith7756afa2012-06-10 05:43:50 +00004405 case Sema::CXXCopyConstructor:
4406 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004407 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004408 break;
4409
4410 case Sema::CXXCopyAssignment:
4411 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004412 if (!S.getLangOpts().CPlusPlus1y)
4413 return false;
4414 // In C++1y, we need to perform overload resolution.
4415 Ctor = false;
4416 break;
4417
Richard Smith7756afa2012-06-10 05:43:50 +00004418 case Sema::CXXDestructor:
4419 case Sema::CXXInvalid:
4420 return false;
4421 }
4422
4423 // -- if the class is a non-empty union, or for each non-empty anonymous
4424 // union member of a non-union class, exactly one non-static data member
4425 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004426 //
4427 // If we squint, this is guaranteed, since exactly one non-static data member
4428 // will be initialized (if the constructor isn't deleted), we just don't know
4429 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004430 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004431 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004432
4433 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004434 if (Ctor && ClassDecl->getNumVBases())
4435 return false;
4436
4437 // C++1y [class.copy]p26:
4438 // -- [the class] is a literal type, and
4439 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004440 return false;
4441
4442 // -- every constructor involved in initializing [...] base class
4443 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004444 // -- the assignment operator selected to copy/move each direct base
4445 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004446 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4447 BEnd = ClassDecl->bases_end();
4448 B != BEnd; ++B) {
4449 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4450 if (!BaseType) continue;
4451
4452 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4453 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4454 return false;
4455 }
4456
4457 // -- every constructor involved in initializing non-static data members
4458 // [...] shall be a constexpr constructor;
4459 // -- every non-static data member and base class sub-object shall be
4460 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004461 // -- for each non-stastic data member of X that is of class type (or array
4462 // thereof), the assignment operator selected to copy/move that member is
4463 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004464 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4465 FEnd = ClassDecl->field_end();
4466 F != FEnd; ++F) {
4467 if (F->isInvalidDecl())
4468 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004469 if (const RecordType *RecordTy =
4470 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004471 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4472 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4473 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004474 }
4475 }
4476
4477 // All OK, it's constexpr!
4478 return true;
4479}
4480
Richard Smithb9d0b762012-07-27 04:22:15 +00004481static Sema::ImplicitExceptionSpecification
4482computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4483 switch (S.getSpecialMember(MD)) {
4484 case Sema::CXXDefaultConstructor:
4485 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4486 case Sema::CXXCopyConstructor:
4487 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4488 case Sema::CXXCopyAssignment:
4489 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4490 case Sema::CXXMoveConstructor:
4491 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4492 case Sema::CXXMoveAssignment:
4493 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4494 case Sema::CXXDestructor:
4495 return S.ComputeDefaultedDtorExceptionSpec(MD);
4496 case Sema::CXXInvalid:
4497 break;
4498 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004499 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4500 "only special members have implicit exception specs");
4501 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004502}
4503
Richard Smithdd25e802012-07-30 23:48:14 +00004504static void
4505updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4506 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4507 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4508 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004509 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4510 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004511}
4512
Reid Kleckneref072032013-08-27 23:08:25 +00004513static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4514 CXXMethodDecl *MD) {
4515 FunctionProtoType::ExtProtoInfo EPI;
4516
4517 // Build an exception specification pointing back at this member.
4518 EPI.ExceptionSpecType = EST_Unevaluated;
4519 EPI.ExceptionSpecDecl = MD;
4520
4521 // Set the calling convention to the default for C++ instance methods.
4522 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4523 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4524 /*IsCXXMethod=*/true));
4525 return EPI;
4526}
4527
Richard Smithb9d0b762012-07-27 04:22:15 +00004528void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4529 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4530 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4531 return;
4532
Richard Smithdd25e802012-07-30 23:48:14 +00004533 // Evaluate the exception specification.
4534 ImplicitExceptionSpecification ExceptSpec =
4535 computeImplicitExceptionSpec(*this, Loc, MD);
4536
4537 // Update the type of the special member to use it.
4538 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4539
4540 // A user-provided destructor can be defined outside the class. When that
4541 // happens, be sure to update the exception specification on both
4542 // declarations.
4543 const FunctionProtoType *CanonicalFPT =
4544 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4545 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4546 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4547 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004548}
4549
Richard Smith3003e1d2012-05-15 04:39:51 +00004550void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4551 CXXRecordDecl *RD = MD->getParent();
4552 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004553
Richard Smith3003e1d2012-05-15 04:39:51 +00004554 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4555 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004556
4557 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004558 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004559 bool First = MD == MD->getCanonicalDecl();
4560
4561 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004562
4563 // C++11 [dcl.fct.def.default]p1:
4564 // A function that is explicitly defaulted shall
4565 // -- be a special member function (checked elsewhere),
4566 // -- have the same type (except for ref-qualifiers, and except that a
4567 // copy operation can take a non-const reference) as an implicit
4568 // declaration, and
4569 // -- not have default arguments.
4570 unsigned ExpectedParams = 1;
4571 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4572 ExpectedParams = 0;
4573 if (MD->getNumParams() != ExpectedParams) {
4574 // This also checks for default arguments: a copy or move constructor with a
4575 // default argument is classified as a default constructor, and assignment
4576 // operations and destructors can't have default arguments.
4577 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4578 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004579 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004580 } else if (MD->isVariadic()) {
4581 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4582 << CSM << MD->getSourceRange();
4583 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004584 }
4585
Richard Smith3003e1d2012-05-15 04:39:51 +00004586 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004587
Richard Smith7756afa2012-06-10 05:43:50 +00004588 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004589 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004590 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004591 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004592 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004593
Richard Smith3003e1d2012-05-15 04:39:51 +00004594 QualType ReturnType = Context.VoidTy;
4595 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4596 // Check for return type matching.
4597 ReturnType = Type->getResultType();
4598 QualType ExpectedReturnType =
4599 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4600 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4601 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4602 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4603 HadError = true;
4604 }
4605
4606 // A defaulted special member cannot have cv-qualifiers.
4607 if (Type->getTypeQuals()) {
4608 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004609 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004610 HadError = true;
4611 }
4612 }
4613
4614 // Check for parameter type matching.
4615 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004616 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004617 if (ExpectedParams && ArgType->isReferenceType()) {
4618 // Argument must be reference to possibly-const T.
4619 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004620 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004621
4622 if (ReferentType.isVolatileQualified()) {
4623 Diag(MD->getLocation(),
4624 diag::err_defaulted_special_member_volatile_param) << CSM;
4625 HadError = true;
4626 }
4627
Richard Smith7756afa2012-06-10 05:43:50 +00004628 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004629 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4630 Diag(MD->getLocation(),
4631 diag::err_defaulted_special_member_copy_const_param)
4632 << (CSM == CXXCopyAssignment);
4633 // FIXME: Explain why this special member can't be const.
4634 } else {
4635 Diag(MD->getLocation(),
4636 diag::err_defaulted_special_member_move_const_param)
4637 << (CSM == CXXMoveAssignment);
4638 }
4639 HadError = true;
4640 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004641 } else if (ExpectedParams) {
4642 // A copy assignment operator can take its argument by value, but a
4643 // defaulted one cannot.
4644 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004645 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004646 HadError = true;
4647 }
Sean Huntbe631222011-05-17 20:44:43 +00004648
Richard Smith61802452011-12-22 02:22:31 +00004649 // C++11 [dcl.fct.def.default]p2:
4650 // An explicitly-defaulted function may be declared constexpr only if it
4651 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004652 // Do not apply this rule to members of class templates, since core issue 1358
4653 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004654 // functions which cannot be constexpr (for non-constructors in C++11 and for
4655 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004656 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4657 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004658 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4659 : isa<CXXConstructorDecl>(MD)) &&
4660 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004661 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4662 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004663 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004664 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004665 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004666
Richard Smith61802452011-12-22 02:22:31 +00004667 // and may have an explicit exception-specification only if it is compatible
4668 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004669 if (Type->hasExceptionSpec()) {
4670 // Delay the check if this is the first declaration of the special member,
4671 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004672 if (First) {
4673 // If the exception specification needs to be instantiated, do so now,
4674 // before we clobber it with an EST_Unevaluated specification below.
4675 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4676 InstantiateExceptionSpec(MD->getLocStart(), MD);
4677 Type = MD->getType()->getAs<FunctionProtoType>();
4678 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004679 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004680 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004681 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4682 }
Richard Smith61802452011-12-22 02:22:31 +00004683
4684 // If a function is explicitly defaulted on its first declaration,
4685 if (First) {
4686 // -- it is implicitly considered to be constexpr if the implicit
4687 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004688 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004689
Richard Smith3003e1d2012-05-15 04:39:51 +00004690 // -- it is implicitly considered to have the same exception-specification
4691 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004692 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4693 EPI.ExceptionSpecType = EST_Unevaluated;
4694 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004695 MD->setType(Context.getFunctionType(ReturnType,
4696 ArrayRef<QualType>(&ArgType,
4697 ExpectedParams),
4698 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004699 }
4700
Richard Smith3003e1d2012-05-15 04:39:51 +00004701 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004702 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004703 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004704 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004705 // C++11 [dcl.fct.def.default]p4:
4706 // [For a] user-provided explicitly-defaulted function [...] if such a
4707 // function is implicitly defined as deleted, the program is ill-formed.
4708 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4709 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004710 }
4711 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004712
Richard Smith3003e1d2012-05-15 04:39:51 +00004713 if (HadError)
4714 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004715}
4716
Richard Smith1d28caf2012-12-11 01:14:52 +00004717/// Check whether the exception specification provided for an
4718/// explicitly-defaulted special member matches the exception specification
4719/// that would have been generated for an implicit special member, per
4720/// C++11 [dcl.fct.def.default]p2.
4721void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4722 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4723 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004724 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4725 /*IsCXXMethod=*/true);
4726 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004727 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4728 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004729 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004730
4731 // Ensure that it matches.
4732 CheckEquivalentExceptionSpec(
4733 PDiag(diag::err_incorrect_defaulted_exception_spec)
4734 << getSpecialMember(MD), PDiag(),
4735 ImplicitType, SourceLocation(),
4736 SpecifiedType, MD->getLocation());
4737}
4738
4739void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4740 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4741 I != N; ++I)
4742 CheckExplicitlyDefaultedMemberExceptionSpec(
4743 DelayedDefaultedMemberExceptionSpecs[I].first,
4744 DelayedDefaultedMemberExceptionSpecs[I].second);
4745
4746 DelayedDefaultedMemberExceptionSpecs.clear();
4747}
4748
Richard Smith7d5088a2012-02-18 02:02:13 +00004749namespace {
4750struct SpecialMemberDeletionInfo {
4751 Sema &S;
4752 CXXMethodDecl *MD;
4753 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004754 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004755
4756 // Properties of the special member, computed for convenience.
4757 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4758 SourceLocation Loc;
4759
4760 bool AllFieldsAreConst;
4761
4762 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004763 Sema::CXXSpecialMember CSM, bool Diagnose)
4764 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004765 IsConstructor(false), IsAssignment(false), IsMove(false),
4766 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4767 AllFieldsAreConst(true) {
4768 switch (CSM) {
4769 case Sema::CXXDefaultConstructor:
4770 case Sema::CXXCopyConstructor:
4771 IsConstructor = true;
4772 break;
4773 case Sema::CXXMoveConstructor:
4774 IsConstructor = true;
4775 IsMove = true;
4776 break;
4777 case Sema::CXXCopyAssignment:
4778 IsAssignment = true;
4779 break;
4780 case Sema::CXXMoveAssignment:
4781 IsAssignment = true;
4782 IsMove = true;
4783 break;
4784 case Sema::CXXDestructor:
4785 break;
4786 case Sema::CXXInvalid:
4787 llvm_unreachable("invalid special member kind");
4788 }
4789
4790 if (MD->getNumParams()) {
4791 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4792 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4793 }
4794 }
4795
4796 bool inUnion() const { return MD->getParent()->isUnion(); }
4797
4798 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004799 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4800 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004801 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004802 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4803 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4804 Quals = 0;
4805 return S.LookupSpecialMember(Class, CSM,
4806 ConstArg || (Quals & Qualifiers::Const),
4807 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004808 MD->getRefQualifier() == RQ_RValue,
4809 TQ & Qualifiers::Const,
4810 TQ & Qualifiers::Volatile);
4811 }
4812
Richard Smith6c4c36c2012-03-30 20:53:28 +00004813 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004814
Richard Smith6c4c36c2012-03-30 20:53:28 +00004815 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004816 bool shouldDeleteForField(FieldDecl *FD);
4817 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004818
Richard Smith517bb842012-07-18 03:51:16 +00004819 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4820 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004821 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4822 Sema::SpecialMemberOverloadResult *SMOR,
4823 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004824
4825 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004826};
4827}
4828
John McCall12d8d802012-04-09 20:53:23 +00004829/// Is the given special member inaccessible when used on the given
4830/// sub-object.
4831bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4832 CXXMethodDecl *target) {
4833 /// If we're operating on a base class, the object type is the
4834 /// type of this special member.
4835 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004836 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004837 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4838 objectTy = S.Context.getTypeDeclType(MD->getParent());
4839 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4840
4841 // If we're operating on a field, the object type is the type of the field.
4842 } else {
4843 objectTy = S.Context.getTypeDeclType(target->getParent());
4844 }
4845
4846 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4847}
4848
Richard Smith6c4c36c2012-03-30 20:53:28 +00004849/// Check whether we should delete a special member due to the implicit
4850/// definition containing a call to a special member of a subobject.
4851bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4852 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4853 bool IsDtorCallInCtor) {
4854 CXXMethodDecl *Decl = SMOR->getMethod();
4855 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4856
4857 int DiagKind = -1;
4858
4859 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4860 DiagKind = !Decl ? 0 : 1;
4861 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4862 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004863 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004864 DiagKind = 3;
4865 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4866 !Decl->isTrivial()) {
4867 // A member of a union must have a trivial corresponding special member.
4868 // As a weird special case, a destructor call from a union's constructor
4869 // must be accessible and non-deleted, but need not be trivial. Such a
4870 // destructor is never actually called, but is semantically checked as
4871 // if it were.
4872 DiagKind = 4;
4873 }
4874
4875 if (DiagKind == -1)
4876 return false;
4877
4878 if (Diagnose) {
4879 if (Field) {
4880 S.Diag(Field->getLocation(),
4881 diag::note_deleted_special_member_class_subobject)
4882 << CSM << MD->getParent() << /*IsField*/true
4883 << Field << DiagKind << IsDtorCallInCtor;
4884 } else {
4885 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4886 S.Diag(Base->getLocStart(),
4887 diag::note_deleted_special_member_class_subobject)
4888 << CSM << MD->getParent() << /*IsField*/false
4889 << Base->getType() << DiagKind << IsDtorCallInCtor;
4890 }
4891
4892 if (DiagKind == 1)
4893 S.NoteDeletedFunction(Decl);
4894 // FIXME: Explain inaccessibility if DiagKind == 3.
4895 }
4896
4897 return true;
4898}
4899
Richard Smith9a561d52012-02-26 09:11:52 +00004900/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004901/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004902bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004903 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004904 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004905
4906 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004907 // -- any direct or virtual base class, or non-static data member with no
4908 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004909 // either M has no default constructor or overload resolution as applied
4910 // to M's default constructor results in an ambiguity or in a function
4911 // that is deleted or inaccessible
4912 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4913 // -- a direct or virtual base class B that cannot be copied/moved because
4914 // overload resolution, as applied to B's corresponding special member,
4915 // results in an ambiguity or a function that is deleted or inaccessible
4916 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004917 // C++11 [class.dtor]p5:
4918 // -- any direct or virtual base class [...] has a type with a destructor
4919 // that is deleted or inaccessible
4920 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004921 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004922 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004923 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004924
Richard Smith6c4c36c2012-03-30 20:53:28 +00004925 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4926 // -- any direct or virtual base class or non-static data member has a
4927 // type with a destructor that is deleted or inaccessible
4928 if (IsConstructor) {
4929 Sema::SpecialMemberOverloadResult *SMOR =
4930 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4931 false, false, false, false, false);
4932 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4933 return true;
4934 }
4935
Richard Smith9a561d52012-02-26 09:11:52 +00004936 return false;
4937}
4938
4939/// Check whether we should delete a special member function due to the class
4940/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004941bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004942 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004943 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004944}
4945
4946/// Check whether we should delete a special member function due to the class
4947/// having a particular non-static data member.
4948bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4949 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4950 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4951
4952 if (CSM == Sema::CXXDefaultConstructor) {
4953 // For a default constructor, all references must be initialized in-class
4954 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004955 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4956 if (Diagnose)
4957 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4958 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004959 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004960 }
Richard Smith79363f52012-02-27 06:07:25 +00004961 // C++11 [class.ctor]p5: any non-variant non-static data member of
4962 // const-qualified type (or array thereof) with no
4963 // brace-or-equal-initializer does not have a user-provided default
4964 // constructor.
4965 if (!inUnion() && FieldType.isConstQualified() &&
4966 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004967 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4968 if (Diagnose)
4969 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004970 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004971 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004972 }
4973
4974 if (inUnion() && !FieldType.isConstQualified())
4975 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004976 } else if (CSM == Sema::CXXCopyConstructor) {
4977 // For a copy constructor, data members must not be of rvalue reference
4978 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004979 if (FieldType->isRValueReferenceType()) {
4980 if (Diagnose)
4981 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4982 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004983 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004984 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004985 } else if (IsAssignment) {
4986 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004987 if (FieldType->isReferenceType()) {
4988 if (Diagnose)
4989 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4990 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004991 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004992 }
4993 if (!FieldRecord && FieldType.isConstQualified()) {
4994 // C++11 [class.copy]p23:
4995 // -- a non-static data member of const non-class type (or array thereof)
4996 if (Diagnose)
4997 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004998 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004999 return true;
5000 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005001 }
5002
5003 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005004 // Some additional restrictions exist on the variant members.
5005 if (!inUnion() && FieldRecord->isUnion() &&
5006 FieldRecord->isAnonymousStructOrUnion()) {
5007 bool AllVariantFieldsAreConst = true;
5008
Richard Smithdf8dc862012-03-29 19:00:10 +00005009 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00005010 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5011 UE = FieldRecord->field_end();
5012 UI != UE; ++UI) {
5013 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005014
5015 if (!UnionFieldType.isConstQualified())
5016 AllVariantFieldsAreConst = false;
5017
Richard Smith9a561d52012-02-26 09:11:52 +00005018 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5019 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00005020 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5021 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005022 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005023 }
5024
5025 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005026 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005027 FieldRecord->field_begin() != FieldRecord->field_end()) {
5028 if (Diagnose)
5029 S.Diag(FieldRecord->getLocation(),
5030 diag::note_deleted_default_ctor_all_const)
5031 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005032 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005033 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005034
Richard Smithdf8dc862012-03-29 19:00:10 +00005035 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005036 // This is technically non-conformant, but sanity demands it.
5037 return false;
5038 }
5039
Richard Smith517bb842012-07-18 03:51:16 +00005040 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5041 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005042 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005043 }
5044
5045 return false;
5046}
5047
5048/// C++11 [class.ctor] p5:
5049/// A defaulted default constructor for a class X is defined as deleted if
5050/// X is a union and all of its variant members are of const-qualified type.
5051bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005052 // This is a silly definition, because it gives an empty union a deleted
5053 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005054 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5055 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5056 if (Diagnose)
5057 S.Diag(MD->getParent()->getLocation(),
5058 diag::note_deleted_default_ctor_all_const)
5059 << MD->getParent() << /*not anonymous union*/0;
5060 return true;
5061 }
5062 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005063}
5064
5065/// Determine whether a defaulted special member function should be defined as
5066/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5067/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005068bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5069 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005070 if (MD->isInvalidDecl())
5071 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005072 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005073 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005074 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005075 return false;
5076
Richard Smith7d5088a2012-02-18 02:02:13 +00005077 // C++11 [expr.lambda.prim]p19:
5078 // The closure type associated with a lambda-expression has a
5079 // deleted (8.4.3) default constructor and a deleted copy
5080 // assignment operator.
5081 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005082 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5083 if (Diagnose)
5084 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005085 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005086 }
5087
Richard Smith5bdaac52012-04-02 20:59:25 +00005088 // For an anonymous struct or union, the copy and assignment special members
5089 // will never be used, so skip the check. For an anonymous union declared at
5090 // namespace scope, the constructor and destructor are used.
5091 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5092 RD->isAnonymousStructOrUnion())
5093 return false;
5094
Richard Smith6c4c36c2012-03-30 20:53:28 +00005095 // C++11 [class.copy]p7, p18:
5096 // If the class definition declares a move constructor or move assignment
5097 // operator, an implicitly declared copy constructor or copy assignment
5098 // operator is defined as deleted.
5099 if (MD->isImplicit() &&
5100 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5101 CXXMethodDecl *UserDeclaredMove = 0;
5102
5103 // In Microsoft mode, a user-declared move only causes the deletion of the
5104 // corresponding copy operation, not both copy operations.
5105 if (RD->hasUserDeclaredMoveConstructor() &&
5106 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5107 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005108
5109 // Find any user-declared move constructor.
5110 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5111 E = RD->ctor_end(); I != E; ++I) {
5112 if (I->isMoveConstructor()) {
5113 UserDeclaredMove = *I;
5114 break;
5115 }
5116 }
Richard Smith1c931be2012-04-02 18:40:40 +00005117 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005118 } else if (RD->hasUserDeclaredMoveAssignment() &&
5119 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5120 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005121
5122 // Find any user-declared move assignment operator.
5123 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5124 E = RD->method_end(); I != E; ++I) {
5125 if (I->isMoveAssignmentOperator()) {
5126 UserDeclaredMove = *I;
5127 break;
5128 }
5129 }
Richard Smith1c931be2012-04-02 18:40:40 +00005130 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005131 }
5132
5133 if (UserDeclaredMove) {
5134 Diag(UserDeclaredMove->getLocation(),
5135 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005136 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005137 << UserDeclaredMove->isMoveAssignmentOperator();
5138 return true;
5139 }
5140 }
Sean Hunte16da072011-10-10 06:18:57 +00005141
Richard Smith5bdaac52012-04-02 20:59:25 +00005142 // Do access control from the special member function
5143 ContextRAII MethodContext(*this, MD);
5144
Richard Smith9a561d52012-02-26 09:11:52 +00005145 // C++11 [class.dtor]p5:
5146 // -- for a virtual destructor, lookup of the non-array deallocation function
5147 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005148 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005149 FunctionDecl *OperatorDelete = 0;
5150 DeclarationName Name =
5151 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5152 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005153 OperatorDelete, false)) {
5154 if (Diagnose)
5155 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005156 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005157 }
Richard Smith9a561d52012-02-26 09:11:52 +00005158 }
5159
Richard Smith6c4c36c2012-03-30 20:53:28 +00005160 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005161
Sean Huntcdee3fe2011-05-11 22:34:38 +00005162 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005163 BE = RD->bases_end(); BI != BE; ++BI)
5164 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005165 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005166 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005167
Richard Smithe0883602013-07-22 18:06:23 +00005168 // Per DR1611, do not consider virtual bases of constructors of abstract
5169 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005170 if (!RD->isAbstract() || !SMI.IsConstructor) {
5171 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5172 BE = RD->vbases_end();
5173 BI != BE; ++BI)
5174 if (SMI.shouldDeleteForBase(BI))
5175 return true;
5176 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005177
5178 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005179 FE = RD->field_end(); FI != FE; ++FI)
5180 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005181 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005182 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005183
Richard Smith7d5088a2012-02-18 02:02:13 +00005184 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005185 return true;
5186
5187 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005188}
5189
Richard Smithac713512012-12-08 02:53:02 +00005190/// Perform lookup for a special member of the specified kind, and determine
5191/// whether it is trivial. If the triviality can be determined without the
5192/// lookup, skip it. This is intended for use when determining whether a
5193/// special member of a containing object is trivial, and thus does not ever
5194/// perform overload resolution for default constructors.
5195///
5196/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5197/// member that was most likely to be intended to be trivial, if any.
5198static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5199 Sema::CXXSpecialMember CSM, unsigned Quals,
5200 CXXMethodDecl **Selected) {
5201 if (Selected)
5202 *Selected = 0;
5203
5204 switch (CSM) {
5205 case Sema::CXXInvalid:
5206 llvm_unreachable("not a special member");
5207
5208 case Sema::CXXDefaultConstructor:
5209 // C++11 [class.ctor]p5:
5210 // A default constructor is trivial if:
5211 // - all the [direct subobjects] have trivial default constructors
5212 //
5213 // Note, no overload resolution is performed in this case.
5214 if (RD->hasTrivialDefaultConstructor())
5215 return true;
5216
5217 if (Selected) {
5218 // If there's a default constructor which could have been trivial, dig it
5219 // out. Otherwise, if there's any user-provided default constructor, point
5220 // to that as an example of why there's not a trivial one.
5221 CXXConstructorDecl *DefCtor = 0;
5222 if (RD->needsImplicitDefaultConstructor())
5223 S.DeclareImplicitDefaultConstructor(RD);
5224 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5225 CE = RD->ctor_end(); CI != CE; ++CI) {
5226 if (!CI->isDefaultConstructor())
5227 continue;
5228 DefCtor = *CI;
5229 if (!DefCtor->isUserProvided())
5230 break;
5231 }
5232
5233 *Selected = DefCtor;
5234 }
5235
5236 return false;
5237
5238 case Sema::CXXDestructor:
5239 // C++11 [class.dtor]p5:
5240 // A destructor is trivial if:
5241 // - all the direct [subobjects] have trivial destructors
5242 if (RD->hasTrivialDestructor())
5243 return true;
5244
5245 if (Selected) {
5246 if (RD->needsImplicitDestructor())
5247 S.DeclareImplicitDestructor(RD);
5248 *Selected = RD->getDestructor();
5249 }
5250
5251 return false;
5252
5253 case Sema::CXXCopyConstructor:
5254 // C++11 [class.copy]p12:
5255 // A copy constructor is trivial if:
5256 // - the constructor selected to copy each direct [subobject] is trivial
5257 if (RD->hasTrivialCopyConstructor()) {
5258 if (Quals == Qualifiers::Const)
5259 // We must either select the trivial copy constructor or reach an
5260 // ambiguity; no need to actually perform overload resolution.
5261 return true;
5262 } else if (!Selected) {
5263 return false;
5264 }
5265 // In C++98, we are not supposed to perform overload resolution here, but we
5266 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5267 // cases like B as having a non-trivial copy constructor:
5268 // struct A { template<typename T> A(T&); };
5269 // struct B { mutable A a; };
5270 goto NeedOverloadResolution;
5271
5272 case Sema::CXXCopyAssignment:
5273 // C++11 [class.copy]p25:
5274 // A copy assignment operator is trivial if:
5275 // - the assignment operator selected to copy each direct [subobject] is
5276 // trivial
5277 if (RD->hasTrivialCopyAssignment()) {
5278 if (Quals == Qualifiers::Const)
5279 return true;
5280 } else if (!Selected) {
5281 return false;
5282 }
5283 // In C++98, we are not supposed to perform overload resolution here, but we
5284 // treat that as a language defect.
5285 goto NeedOverloadResolution;
5286
5287 case Sema::CXXMoveConstructor:
5288 case Sema::CXXMoveAssignment:
5289 NeedOverloadResolution:
5290 Sema::SpecialMemberOverloadResult *SMOR =
5291 S.LookupSpecialMember(RD, CSM,
5292 Quals & Qualifiers::Const,
5293 Quals & Qualifiers::Volatile,
5294 /*RValueThis*/false, /*ConstThis*/false,
5295 /*VolatileThis*/false);
5296
5297 // The standard doesn't describe how to behave if the lookup is ambiguous.
5298 // We treat it as not making the member non-trivial, just like the standard
5299 // mandates for the default constructor. This should rarely matter, because
5300 // the member will also be deleted.
5301 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5302 return true;
5303
5304 if (!SMOR->getMethod()) {
5305 assert(SMOR->getKind() ==
5306 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5307 return false;
5308 }
5309
5310 // We deliberately don't check if we found a deleted special member. We're
5311 // not supposed to!
5312 if (Selected)
5313 *Selected = SMOR->getMethod();
5314 return SMOR->getMethod()->isTrivial();
5315 }
5316
5317 llvm_unreachable("unknown special method kind");
5318}
5319
Benjamin Kramera574c892013-02-15 12:30:38 +00005320static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005321 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5322 CI != CE; ++CI)
5323 if (!CI->isImplicit())
5324 return *CI;
5325
5326 // Look for constructor templates.
5327 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5328 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5329 if (CXXConstructorDecl *CD =
5330 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5331 return CD;
5332 }
5333
5334 return 0;
5335}
5336
5337/// The kind of subobject we are checking for triviality. The values of this
5338/// enumeration are used in diagnostics.
5339enum TrivialSubobjectKind {
5340 /// The subobject is a base class.
5341 TSK_BaseClass,
5342 /// The subobject is a non-static data member.
5343 TSK_Field,
5344 /// The object is actually the complete object.
5345 TSK_CompleteObject
5346};
5347
5348/// Check whether the special member selected for a given type would be trivial.
5349static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5350 QualType SubType,
5351 Sema::CXXSpecialMember CSM,
5352 TrivialSubobjectKind Kind,
5353 bool Diagnose) {
5354 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5355 if (!SubRD)
5356 return true;
5357
5358 CXXMethodDecl *Selected;
5359 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5360 Diagnose ? &Selected : 0))
5361 return true;
5362
5363 if (Diagnose) {
5364 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5365 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5366 << Kind << SubType.getUnqualifiedType();
5367 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5368 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5369 } else if (!Selected)
5370 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5371 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5372 else if (Selected->isUserProvided()) {
5373 if (Kind == TSK_CompleteObject)
5374 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5375 << Kind << SubType.getUnqualifiedType() << CSM;
5376 else {
5377 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5378 << Kind << SubType.getUnqualifiedType() << CSM;
5379 S.Diag(Selected->getLocation(), diag::note_declared_at);
5380 }
5381 } else {
5382 if (Kind != TSK_CompleteObject)
5383 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5384 << Kind << SubType.getUnqualifiedType() << CSM;
5385
5386 // Explain why the defaulted or deleted special member isn't trivial.
5387 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5388 }
5389 }
5390
5391 return false;
5392}
5393
5394/// Check whether the members of a class type allow a special member to be
5395/// trivial.
5396static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5397 Sema::CXXSpecialMember CSM,
5398 bool ConstArg, bool Diagnose) {
5399 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5400 FE = RD->field_end(); FI != FE; ++FI) {
5401 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5402 continue;
5403
5404 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5405
5406 // Pretend anonymous struct or union members are members of this class.
5407 if (FI->isAnonymousStructOrUnion()) {
5408 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5409 CSM, ConstArg, Diagnose))
5410 return false;
5411 continue;
5412 }
5413
5414 // C++11 [class.ctor]p5:
5415 // A default constructor is trivial if [...]
5416 // -- no non-static data member of its class has a
5417 // brace-or-equal-initializer
5418 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5419 if (Diagnose)
5420 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5421 return false;
5422 }
5423
5424 // Objective C ARC 4.3.5:
5425 // [...] nontrivally ownership-qualified types are [...] not trivially
5426 // default constructible, copy constructible, move constructible, copy
5427 // assignable, move assignable, or destructible [...]
5428 if (S.getLangOpts().ObjCAutoRefCount &&
5429 FieldType.hasNonTrivialObjCLifetime()) {
5430 if (Diagnose)
5431 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5432 << RD << FieldType.getObjCLifetime();
5433 return false;
5434 }
5435
5436 if (ConstArg && !FI->isMutable())
5437 FieldType.addConst();
5438 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5439 TSK_Field, Diagnose))
5440 return false;
5441 }
5442
5443 return true;
5444}
5445
5446/// Diagnose why the specified class does not have a trivial special member of
5447/// the given kind.
5448void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5449 QualType Ty = Context.getRecordType(RD);
5450 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5451 Ty.addConst();
5452
5453 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5454 TSK_CompleteObject, /*Diagnose*/true);
5455}
5456
5457/// Determine whether a defaulted or deleted special member function is trivial,
5458/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5459/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5460bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5461 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005462 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5463
5464 CXXRecordDecl *RD = MD->getParent();
5465
5466 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005467
5468 // C++11 [class.copy]p12, p25:
5469 // A [special member] is trivial if its declared parameter type is the same
5470 // as if it had been implicitly declared [...]
5471 switch (CSM) {
5472 case CXXDefaultConstructor:
5473 case CXXDestructor:
5474 // Trivial default constructors and destructors cannot have parameters.
5475 break;
5476
5477 case CXXCopyConstructor:
5478 case CXXCopyAssignment: {
5479 // Trivial copy operations always have const, non-volatile parameter types.
5480 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005481 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005482 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5483 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5484 if (Diagnose)
5485 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5486 << Param0->getSourceRange() << Param0->getType()
5487 << Context.getLValueReferenceType(
5488 Context.getRecordType(RD).withConst());
5489 return false;
5490 }
5491 break;
5492 }
5493
5494 case CXXMoveConstructor:
5495 case CXXMoveAssignment: {
5496 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005497 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005498 const RValueReferenceType *RT =
5499 Param0->getType()->getAs<RValueReferenceType>();
5500 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5501 if (Diagnose)
5502 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5503 << Param0->getSourceRange() << Param0->getType()
5504 << Context.getRValueReferenceType(Context.getRecordType(RD));
5505 return false;
5506 }
5507 break;
5508 }
5509
5510 case CXXInvalid:
5511 llvm_unreachable("not a special member");
5512 }
5513
5514 // FIXME: We require that the parameter-declaration-clause is equivalent to
5515 // that of an implicit declaration, not just that the declared parameter type
5516 // matches, in order to prevent absuridities like a function simultaneously
5517 // being a trivial copy constructor and a non-trivial default constructor.
5518 // This issue has not yet been assigned a core issue number.
5519 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5520 if (Diagnose)
5521 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5522 diag::note_nontrivial_default_arg)
5523 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5524 return false;
5525 }
5526 if (MD->isVariadic()) {
5527 if (Diagnose)
5528 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5529 return false;
5530 }
5531
5532 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5533 // A copy/move [constructor or assignment operator] is trivial if
5534 // -- the [member] selected to copy/move each direct base class subobject
5535 // is trivial
5536 //
5537 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5538 // A [default constructor or destructor] is trivial if
5539 // -- all the direct base classes have trivial [default constructors or
5540 // destructors]
5541 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5542 BE = RD->bases_end(); BI != BE; ++BI)
5543 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5544 ConstArg ? BI->getType().withConst()
5545 : BI->getType(),
5546 CSM, TSK_BaseClass, Diagnose))
5547 return false;
5548
5549 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5550 // A copy/move [constructor or assignment operator] for a class X is
5551 // trivial if
5552 // -- for each non-static data member of X that is of class type (or array
5553 // thereof), the constructor selected to copy/move that member is
5554 // trivial
5555 //
5556 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5557 // A [default constructor or destructor] is trivial if
5558 // -- for all of the non-static data members of its class that are of class
5559 // type (or array thereof), each such class has a trivial [default
5560 // constructor or destructor]
5561 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5562 return false;
5563
5564 // C++11 [class.dtor]p5:
5565 // A destructor is trivial if [...]
5566 // -- the destructor is not virtual
5567 if (CSM == CXXDestructor && MD->isVirtual()) {
5568 if (Diagnose)
5569 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5570 return false;
5571 }
5572
5573 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5574 // A [special member] for class X is trivial if [...]
5575 // -- class X has no virtual functions and no virtual base classes
5576 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5577 if (!Diagnose)
5578 return false;
5579
5580 if (RD->getNumVBases()) {
5581 // Check for virtual bases. We already know that the corresponding
5582 // member in all bases is trivial, so vbases must all be direct.
5583 CXXBaseSpecifier &BS = *RD->vbases_begin();
5584 assert(BS.isVirtual());
5585 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5586 return false;
5587 }
5588
5589 // Must have a virtual method.
5590 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5591 ME = RD->method_end(); MI != ME; ++MI) {
5592 if (MI->isVirtual()) {
5593 SourceLocation MLoc = MI->getLocStart();
5594 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5595 return false;
5596 }
5597 }
5598
5599 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5600 }
5601
5602 // Looks like it's trivial!
5603 return true;
5604}
5605
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005606/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005607namespace {
5608 struct FindHiddenVirtualMethodData {
5609 Sema *S;
5610 CXXMethodDecl *Method;
5611 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005612 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005613 };
5614}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005615
David Blaikie5f750682012-10-19 00:53:08 +00005616/// \brief Check whether any most overriden method from MD in Methods
5617static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5618 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5619 if (MD->size_overridden_methods() == 0)
5620 return Methods.count(MD->getCanonicalDecl());
5621 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5622 E = MD->end_overridden_methods();
5623 I != E; ++I)
5624 if (CheckMostOverridenMethods(*I, Methods))
5625 return true;
5626 return false;
5627}
5628
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005629/// \brief Member lookup function that determines whether a given C++
5630/// method overloads virtual methods in a base class without overriding any,
5631/// to be used with CXXRecordDecl::lookupInBases().
5632static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5633 CXXBasePath &Path,
5634 void *UserData) {
5635 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5636
5637 FindHiddenVirtualMethodData &Data
5638 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5639
5640 DeclarationName Name = Data.Method->getDeclName();
5641 assert(Name.getNameKind() == DeclarationName::Identifier);
5642
5643 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005644 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005645 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005646 !Path.Decls.empty();
5647 Path.Decls = Path.Decls.slice(1)) {
5648 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005649 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005650 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005651 foundSameNameMethod = true;
5652 // Interested only in hidden virtual methods.
5653 if (!MD->isVirtual())
5654 continue;
5655 // If the method we are checking overrides a method from its base
5656 // don't warn about the other overloaded methods.
5657 if (!Data.S->IsOverload(Data.Method, MD, false))
5658 return true;
5659 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005660 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005661 overloadedMethods.push_back(MD);
5662 }
5663 }
5664
5665 if (foundSameNameMethod)
5666 Data.OverloadedMethods.append(overloadedMethods.begin(),
5667 overloadedMethods.end());
5668 return foundSameNameMethod;
5669}
5670
David Blaikie5f750682012-10-19 00:53:08 +00005671/// \brief Add the most overriden methods from MD to Methods
5672static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5673 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5674 if (MD->size_overridden_methods() == 0)
5675 Methods.insert(MD->getCanonicalDecl());
5676 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5677 E = MD->end_overridden_methods();
5678 I != E; ++I)
5679 AddMostOverridenMethods(*I, Methods);
5680}
5681
Eli Friedmandae92712013-09-05 23:51:03 +00005682/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005683/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005684void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5685 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005686 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005687 return;
5688
5689 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5690 /*bool RecordPaths=*/false,
5691 /*bool DetectVirtual=*/false);
5692 FindHiddenVirtualMethodData Data;
5693 Data.Method = MD;
5694 Data.S = this;
5695
5696 // Keep the base methods that were overriden or introduced in the subclass
5697 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005698 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005699 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5700 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5701 NamedDecl *ND = *I;
5702 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005703 ND = shad->getTargetDecl();
5704 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5705 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005706 }
5707
Eli Friedmandae92712013-09-05 23:51:03 +00005708 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5709 OverloadedMethods = Data.OverloadedMethods;
5710}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005711
Eli Friedmandae92712013-09-05 23:51:03 +00005712void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5713 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5714 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5715 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5716 PartialDiagnostic PD = PDiag(
5717 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5718 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5719 Diag(overloadedMD->getLocation(), PD);
5720 }
5721}
5722
5723/// \brief Diagnose methods which overload virtual methods in a base class
5724/// without overriding any.
5725void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5726 if (MD->isInvalidDecl())
5727 return;
5728
5729 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5730 MD->getLocation()) == DiagnosticsEngine::Ignored)
5731 return;
5732
5733 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5734 FindHiddenVirtualMethods(MD, OverloadedMethods);
5735 if (!OverloadedMethods.empty()) {
5736 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5737 << MD << (OverloadedMethods.size() > 1);
5738
5739 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005740 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005741}
5742
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005743void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005744 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005745 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005746 SourceLocation RBrac,
5747 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005748 if (!TagDecl)
5749 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005750
Douglas Gregor42af25f2009-05-11 19:58:34 +00005751 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005752
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005753 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5754 if (l->getKind() != AttributeList::AT_Visibility)
5755 continue;
5756 l->setInvalid();
5757 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5758 l->getName();
5759 }
5760
David Blaikie77b6de02011-09-22 02:58:26 +00005761 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005762 // strict aliasing violation!
5763 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005764 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005765
Douglas Gregor23c94db2010-07-02 17:43:08 +00005766 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005767 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005768}
5769
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005770/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5771/// special functions, such as the default constructor, copy
5772/// constructor, or destructor, to the given C++ class (C++
5773/// [special]p1). This routine can only be executed just before the
5774/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005775void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005776 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005777 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005778
Richard Smithbc2a35d2012-12-08 08:32:28 +00005779 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005780 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005781
Richard Smithbc2a35d2012-12-08 08:32:28 +00005782 // If the properties or semantics of the copy constructor couldn't be
5783 // determined while the class was being declared, force a declaration
5784 // of it now.
5785 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5786 DeclareImplicitCopyConstructor(ClassDecl);
5787 }
5788
Richard Smith80ad52f2013-01-02 11:42:31 +00005789 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005790 ++ASTContext::NumImplicitMoveConstructors;
5791
Richard Smithbc2a35d2012-12-08 08:32:28 +00005792 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5793 DeclareImplicitMoveConstructor(ClassDecl);
5794 }
5795
Douglas Gregora376d102010-07-02 21:50:04 +00005796 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5797 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005798
5799 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005800 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005801 // it shows up in the right place in the vtable and that we diagnose
5802 // problems with the implicit exception specification.
5803 if (ClassDecl->isDynamicClass() ||
5804 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005805 DeclareImplicitCopyAssignment(ClassDecl);
5806 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005807
Richard Smith80ad52f2013-01-02 11:42:31 +00005808 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005809 ++ASTContext::NumImplicitMoveAssignmentOperators;
5810
5811 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005812 if (ClassDecl->isDynamicClass() ||
5813 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005814 DeclareImplicitMoveAssignment(ClassDecl);
5815 }
5816
Douglas Gregor4923aa22010-07-02 20:37:36 +00005817 if (!ClassDecl->hasUserDeclaredDestructor()) {
5818 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005819
5820 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005821 // have to declare the destructor immediately. This ensures that, e.g., it
5822 // shows up in the right place in the vtable and that we diagnose problems
5823 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005824 if (ClassDecl->isDynamicClass() ||
5825 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005826 DeclareImplicitDestructor(ClassDecl);
5827 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005828}
5829
Francois Pichet8387e2a2011-04-22 22:18:13 +00005830void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5831 if (!D)
5832 return;
5833
5834 int NumParamList = D->getNumTemplateParameterLists();
5835 for (int i = 0; i < NumParamList; i++) {
5836 TemplateParameterList* Params = D->getTemplateParameterList(i);
5837 for (TemplateParameterList::iterator Param = Params->begin(),
5838 ParamEnd = Params->end();
5839 Param != ParamEnd; ++Param) {
5840 NamedDecl *Named = cast<NamedDecl>(*Param);
5841 if (Named->getDeclName()) {
5842 S->AddDecl(Named);
5843 IdResolver.AddDecl(Named);
5844 }
5845 }
5846 }
5847}
5848
John McCalld226f652010-08-21 09:40:31 +00005849void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005850 if (!D)
5851 return;
5852
5853 TemplateParameterList *Params = 0;
5854 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5855 Params = Template->getTemplateParameters();
5856 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5857 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5858 Params = PartialSpec->getTemplateParameters();
5859 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005860 return;
5861
Douglas Gregor6569d682009-05-27 23:11:45 +00005862 for (TemplateParameterList::iterator Param = Params->begin(),
5863 ParamEnd = Params->end();
5864 Param != ParamEnd; ++Param) {
5865 NamedDecl *Named = cast<NamedDecl>(*Param);
5866 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005867 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005868 IdResolver.AddDecl(Named);
5869 }
5870 }
5871}
5872
John McCalld226f652010-08-21 09:40:31 +00005873void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005874 if (!RecordD) return;
5875 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005876 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005877 PushDeclContext(S, Record);
5878}
5879
John McCalld226f652010-08-21 09:40:31 +00005880void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005881 if (!RecordD) return;
5882 PopDeclContext();
5883}
5884
Douglas Gregor72b505b2008-12-16 21:30:33 +00005885/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5886/// parsing a top-level (non-nested) C++ class, and we are now
5887/// parsing those parts of the given Method declaration that could
5888/// not be parsed earlier (C++ [class.mem]p2), such as default
5889/// arguments. This action should enter the scope of the given
5890/// Method declaration as if we had just parsed the qualified method
5891/// name. However, it should not bring the parameters into scope;
5892/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005893void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005894}
5895
5896/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5897/// C++ method declaration. We're (re-)introducing the given
5898/// function parameter into scope for use in parsing later parts of
5899/// the method declaration. For example, we could see an
5900/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005901void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005902 if (!ParamD)
5903 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005904
John McCalld226f652010-08-21 09:40:31 +00005905 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005906
5907 // If this parameter has an unparsed default argument, clear it out
5908 // to make way for the parsed default argument.
5909 if (Param->hasUnparsedDefaultArg())
5910 Param->setDefaultArg(0);
5911
John McCalld226f652010-08-21 09:40:31 +00005912 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005913 if (Param->getDeclName())
5914 IdResolver.AddDecl(Param);
5915}
5916
5917/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5918/// processing the delayed method declaration for Method. The method
5919/// declaration is now considered finished. There may be a separate
5920/// ActOnStartOfFunctionDef action later (not necessarily
5921/// immediately!) for this method, if it was also defined inside the
5922/// class body.
John McCalld226f652010-08-21 09:40:31 +00005923void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005924 if (!MethodD)
5925 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005926
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005927 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005928
John McCalld226f652010-08-21 09:40:31 +00005929 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005930
5931 // Now that we have our default arguments, check the constructor
5932 // again. It could produce additional diagnostics or affect whether
5933 // the class has implicitly-declared destructors, among other
5934 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005935 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5936 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005937
5938 // Check the default arguments, which we may have added.
5939 if (!Method->isInvalidDecl())
5940 CheckCXXDefaultArguments(Method);
5941}
5942
Douglas Gregor42a552f2008-11-05 20:51:48 +00005943/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005944/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005945/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005946/// emit diagnostics and set the invalid bit to true. In any case, the type
5947/// will be updated to reflect a well-formed type for the constructor and
5948/// returned.
5949QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005950 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005951 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005952
5953 // C++ [class.ctor]p3:
5954 // A constructor shall not be virtual (10.3) or static (9.4). A
5955 // constructor can be invoked for a const, volatile or const
5956 // volatile object. A constructor shall not be declared const,
5957 // volatile, or const volatile (9.3.2).
5958 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005959 if (!D.isInvalidType())
5960 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5961 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5962 << SourceRange(D.getIdentifierLoc());
5963 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005964 }
John McCalld931b082010-08-26 03:08:43 +00005965 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005966 if (!D.isInvalidType())
5967 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5968 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5969 << SourceRange(D.getIdentifierLoc());
5970 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005971 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005972 }
Mike Stump1eb44332009-09-09 15:08:12 +00005973
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005974 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005975 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005976 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5978 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005979 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5981 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005982 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005983 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5984 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005985 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005986 }
Mike Stump1eb44332009-09-09 15:08:12 +00005987
Douglas Gregorc938c162011-01-26 05:01:58 +00005988 // C++0x [class.ctor]p4:
5989 // A constructor shall not be declared with a ref-qualifier.
5990 if (FTI.hasRefQualifier()) {
5991 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5992 << FTI.RefQualifierIsLValueRef
5993 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5994 D.setInvalidType();
5995 }
5996
Douglas Gregor42a552f2008-11-05 20:51:48 +00005997 // Rebuild the function type "R" without any type qualifiers (in
5998 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005999 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006000 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006001 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6002 return R;
6003
6004 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6005 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006006 EPI.RefQualifier = RQ_None;
6007
Richard Smith07b0fdc2013-03-18 21:12:30 +00006008 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006009}
6010
Douglas Gregor72b505b2008-12-16 21:30:33 +00006011/// CheckConstructor - Checks a fully-formed constructor for
6012/// well-formedness, issuing any diagnostics required. Returns true if
6013/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006014void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006015 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006016 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6017 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006018 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006019
6020 // C++ [class.copy]p3:
6021 // A declaration of a constructor for a class X is ill-formed if
6022 // its first parameter is of type (optionally cv-qualified) X and
6023 // either there are no other parameters or else all other
6024 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006025 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006026 ((Constructor->getNumParams() == 1) ||
6027 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006028 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6029 Constructor->getTemplateSpecializationKind()
6030 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006031 QualType ParamType = Constructor->getParamDecl(0)->getType();
6032 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6033 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006034 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006035 const char *ConstRef
6036 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6037 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006038 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006039 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006040
6041 // FIXME: Rather that making the constructor invalid, we should endeavor
6042 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006043 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006044 }
6045 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006046}
6047
John McCall15442822010-08-04 01:04:25 +00006048/// CheckDestructor - Checks a fully-formed destructor definition for
6049/// well-formedness, issuing any diagnostics required. Returns true
6050/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006051bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006052 CXXRecordDecl *RD = Destructor->getParent();
6053
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006054 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006055 SourceLocation Loc;
6056
6057 if (!Destructor->isImplicit())
6058 Loc = Destructor->getLocation();
6059 else
6060 Loc = RD->getLocation();
6061
6062 // If we have a virtual destructor, look up the deallocation function
6063 FunctionDecl *OperatorDelete = 0;
6064 DeclarationName Name =
6065 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006066 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006067 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006068
Eli Friedman5f2987c2012-02-02 03:46:19 +00006069 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006070
6071 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006072 }
Anders Carlsson37909802009-11-30 21:24:50 +00006073
6074 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006075}
6076
Mike Stump1eb44332009-09-09 15:08:12 +00006077static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006078FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6079 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6080 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006081 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006082}
6083
Douglas Gregor42a552f2008-11-05 20:51:48 +00006084/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6085/// the well-formednes of the destructor declarator @p D with type @p
6086/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006087/// emit diagnostics and set the declarator to invalid. Even if this happens,
6088/// will be updated to reflect a well-formed type for the destructor and
6089/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006090QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006091 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006092 // C++ [class.dtor]p1:
6093 // [...] A typedef-name that names a class is a class-name
6094 // (7.1.3); however, a typedef-name that names a class shall not
6095 // be used as the identifier in the declarator for a destructor
6096 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006097 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006098 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006099 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006100 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006101 else if (const TemplateSpecializationType *TST =
6102 DeclaratorType->getAs<TemplateSpecializationType>())
6103 if (TST->isTypeAlias())
6104 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6105 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006106
6107 // C++ [class.dtor]p2:
6108 // A destructor is used to destroy objects of its class type. A
6109 // destructor takes no parameters, and no return type can be
6110 // specified for it (not even void). The address of a destructor
6111 // shall not be taken. A destructor shall not be static. A
6112 // destructor can be invoked for a const, volatile or const
6113 // volatile object. A destructor shall not be declared const,
6114 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006115 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006116 if (!D.isInvalidType())
6117 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6118 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006119 << SourceRange(D.getIdentifierLoc())
6120 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6121
John McCalld931b082010-08-26 03:08:43 +00006122 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006123 }
Chris Lattner65401802009-04-25 08:28:21 +00006124 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006125 // Destructors don't have return types, but the parser will
6126 // happily parse something like:
6127 //
6128 // class X {
6129 // float ~X();
6130 // };
6131 //
6132 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006133 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6134 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6135 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006136 }
Mike Stump1eb44332009-09-09 15:08:12 +00006137
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006138 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006139 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006140 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6142 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006143 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006144 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6145 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006146 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006147 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6148 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006149 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006150 }
6151
Douglas Gregorc938c162011-01-26 05:01:58 +00006152 // C++0x [class.dtor]p2:
6153 // A destructor shall not be declared with a ref-qualifier.
6154 if (FTI.hasRefQualifier()) {
6155 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6156 << FTI.RefQualifierIsLValueRef
6157 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6158 D.setInvalidType();
6159 }
6160
Douglas Gregor42a552f2008-11-05 20:51:48 +00006161 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006162 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006163 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6164
6165 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006166 FTI.freeArgs();
6167 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006168 }
6169
Mike Stump1eb44332009-09-09 15:08:12 +00006170 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006171 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006172 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006173 D.setInvalidType();
6174 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006175
6176 // Rebuild the function type "R" without any type qualifiers or
6177 // parameters (in case any of the errors above fired) and with
6178 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006179 // types.
John McCalle23cf432010-12-14 08:05:40 +00006180 if (!D.isInvalidType())
6181 return R;
6182
Douglas Gregord92ec472010-07-01 05:10:53 +00006183 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006184 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6185 EPI.Variadic = false;
6186 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006187 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006188 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006189}
6190
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006191/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6192/// well-formednes of the conversion function declarator @p D with
6193/// type @p R. If there are any errors in the declarator, this routine
6194/// will emit diagnostics and return true. Otherwise, it will return
6195/// false. Either way, the type @p R will be updated to reflect a
6196/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006197void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006198 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006199 // C++ [class.conv.fct]p1:
6200 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006201 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006202 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006203 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006204 if (!D.isInvalidType())
6205 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006206 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6207 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006208 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006209 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006210 }
John McCalla3f81372010-04-13 00:04:31 +00006211
6212 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6213
Chris Lattner6e475012009-04-25 08:35:12 +00006214 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006215 // Conversion functions don't have return types, but the parser will
6216 // happily parse something like:
6217 //
6218 // class X {
6219 // float operator bool();
6220 // };
6221 //
6222 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006223 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6224 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6225 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006226 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006227 }
6228
John McCalla3f81372010-04-13 00:04:31 +00006229 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6230
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006231 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006232 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006233 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6234
6235 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006236 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006237 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006238 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006239 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006240 D.setInvalidType();
6241 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006242
John McCalla3f81372010-04-13 00:04:31 +00006243 // Diagnose "&operator bool()" and other such nonsense. This
6244 // is actually a gcc extension which we don't support.
6245 if (Proto->getResultType() != ConvType) {
6246 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6247 << Proto->getResultType();
6248 D.setInvalidType();
6249 ConvType = Proto->getResultType();
6250 }
6251
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006252 // C++ [class.conv.fct]p4:
6253 // The conversion-type-id shall not represent a function type nor
6254 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006255 if (ConvType->isArrayType()) {
6256 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6257 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006258 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006259 } else if (ConvType->isFunctionType()) {
6260 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6261 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006262 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006263 }
6264
6265 // Rebuild the function type "R" without any parameters (in case any
6266 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006267 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006268 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006269 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006270
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006271 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006272 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006273 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006274 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006275 diag::warn_cxx98_compat_explicit_conversion_functions :
6276 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006277 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006278}
6279
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006280/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6281/// the declaration of the given C++ conversion function. This routine
6282/// is responsible for recording the conversion function in the C++
6283/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006284Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006285 assert(Conversion && "Expected to receive a conversion function declaration");
6286
Douglas Gregor9d350972008-12-12 08:25:50 +00006287 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006288
6289 // Make sure we aren't redeclaring the conversion function.
6290 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006291
6292 // C++ [class.conv.fct]p1:
6293 // [...] A conversion function is never used to convert a
6294 // (possibly cv-qualified) object to the (possibly cv-qualified)
6295 // same object type (or a reference to it), to a (possibly
6296 // cv-qualified) base class of that type (or a reference to it),
6297 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006298 // FIXME: Suppress this warning if the conversion function ends up being a
6299 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006300 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006301 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006302 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006303 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006304 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6305 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006306 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006307 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006308 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6309 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006310 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006311 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006312 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006313 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006314 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006315 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006316 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006317 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006318 }
6319
Douglas Gregore80622f2010-09-29 04:25:11 +00006320 if (FunctionTemplateDecl *ConversionTemplate
6321 = Conversion->getDescribedFunctionTemplate())
6322 return ConversionTemplate;
6323
John McCalld226f652010-08-21 09:40:31 +00006324 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006325}
6326
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006327//===----------------------------------------------------------------------===//
6328// Namespace Handling
6329//===----------------------------------------------------------------------===//
6330
Richard Smithd1a55a62012-10-04 22:13:39 +00006331/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6332/// reopened.
6333static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6334 SourceLocation Loc,
6335 IdentifierInfo *II, bool *IsInline,
6336 NamespaceDecl *PrevNS) {
6337 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006338
Richard Smithc969e6a2012-10-05 01:46:25 +00006339 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6340 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6341 // inline namespaces, with the intention of bringing names into namespace std.
6342 //
6343 // We support this just well enough to get that case working; this is not
6344 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006345 if (*IsInline && II && II->getName().startswith("__atomic") &&
6346 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006347 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006348 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6349 NS = NS->getPreviousDecl())
6350 NS->setInline(*IsInline);
6351 // Patch up the lookup table for the containing namespace. This isn't really
6352 // correct, but it's good enough for this particular case.
6353 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6354 E = PrevNS->decls_end(); I != E; ++I)
6355 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6356 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6357 return;
6358 }
6359
6360 if (PrevNS->isInline())
6361 // The user probably just forgot the 'inline', so suggest that it
6362 // be added back.
6363 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6364 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6365 else
6366 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6367 << IsInline;
6368
6369 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6370 *IsInline = PrevNS->isInline();
6371}
John McCallea318642010-08-26 09:15:37 +00006372
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006373/// ActOnStartNamespaceDef - This is called at the start of a namespace
6374/// definition.
John McCalld226f652010-08-21 09:40:31 +00006375Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006376 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006377 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006378 SourceLocation IdentLoc,
6379 IdentifierInfo *II,
6380 SourceLocation LBrace,
6381 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006382 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6383 // For anonymous namespace, take the location of the left brace.
6384 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006385 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006386 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006387 bool IsStd = false;
6388 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006389 Scope *DeclRegionScope = NamespcScope->getParent();
6390
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006391 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006392 if (II) {
6393 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006394 // The identifier in an original-namespace-definition shall not
6395 // have been previously defined in the declarative region in
6396 // which the original-namespace-definition appears. The
6397 // identifier in an original-namespace-definition is the name of
6398 // the namespace. Subsequently in that declarative region, it is
6399 // treated as an original-namespace-name.
6400 //
6401 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006402 // look through using directives, just look for any ordinary names.
6403
6404 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006405 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6406 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006407 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006408 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6409 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6410 ++I) {
6411 if ((*I)->getIdentifierNamespace() & IDNS) {
6412 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006413 break;
6414 }
6415 }
6416
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006417 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6418
6419 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006420 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006421 if (IsInline != PrevNS->isInline())
6422 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6423 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006424 } else if (PrevDecl) {
6425 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006426 Diag(Loc, diag::err_redefinition_different_kind)
6427 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006428 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006429 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006430 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006431 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006432 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006433 // This is the first "real" definition of the namespace "std", so update
6434 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006435 PrevNS = getStdNamespace();
6436 IsStd = true;
6437 AddToKnown = !IsInline;
6438 } else {
6439 // We've seen this namespace for the first time.
6440 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006441 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006442 } else {
John McCall9aeed322009-10-01 00:25:31 +00006443 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006444
6445 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006446 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006447 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006448 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006449 } else {
6450 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006451 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006452 }
6453
Richard Smithd1a55a62012-10-04 22:13:39 +00006454 if (PrevNS && IsInline != PrevNS->isInline())
6455 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6456 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006457 }
6458
6459 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6460 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006461 if (IsInvalid)
6462 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006463
6464 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006465
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006466 // FIXME: Should we be merging attributes?
6467 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006468 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006469
6470 if (IsStd)
6471 StdNamespace = Namespc;
6472 if (AddToKnown)
6473 KnownNamespaces[Namespc] = false;
6474
6475 if (II) {
6476 PushOnScopeChains(Namespc, DeclRegionScope);
6477 } else {
6478 // Link the anonymous namespace into its parent.
6479 DeclContext *Parent = CurContext->getRedeclContext();
6480 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6481 TU->setAnonymousNamespace(Namespc);
6482 } else {
6483 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006484 }
John McCall9aeed322009-10-01 00:25:31 +00006485
Douglas Gregora4181472010-03-24 00:46:35 +00006486 CurContext->addDecl(Namespc);
6487
John McCall9aeed322009-10-01 00:25:31 +00006488 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6489 // behaves as if it were replaced by
6490 // namespace unique { /* empty body */ }
6491 // using namespace unique;
6492 // namespace unique { namespace-body }
6493 // where all occurrences of 'unique' in a translation unit are
6494 // replaced by the same identifier and this identifier differs
6495 // from all other identifiers in the entire program.
6496
6497 // We just create the namespace with an empty name and then add an
6498 // implicit using declaration, just like the standard suggests.
6499 //
6500 // CodeGen enforces the "universally unique" aspect by giving all
6501 // declarations semantically contained within an anonymous
6502 // namespace internal linkage.
6503
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006504 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006505 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006506 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006507 /* 'using' */ LBrace,
6508 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006509 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006510 /* identifier */ SourceLocation(),
6511 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006512 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006513 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006514 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006515 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006516 }
6517
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006518 ActOnDocumentableDecl(Namespc);
6519
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006520 // Although we could have an invalid decl (i.e. the namespace name is a
6521 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006522 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6523 // for the namespace has the declarations that showed up in that particular
6524 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006525 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006526 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006527}
6528
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006529/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6530/// is a namespace alias, returns the namespace it points to.
6531static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6532 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6533 return AD->getNamespace();
6534 return dyn_cast_or_null<NamespaceDecl>(D);
6535}
6536
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006537/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6538/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006539void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006540 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6541 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006542 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006543 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006544 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006545 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006546}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006547
John McCall384aff82010-08-25 07:42:41 +00006548CXXRecordDecl *Sema::getStdBadAlloc() const {
6549 return cast_or_null<CXXRecordDecl>(
6550 StdBadAlloc.get(Context.getExternalSource()));
6551}
6552
6553NamespaceDecl *Sema::getStdNamespace() const {
6554 return cast_or_null<NamespaceDecl>(
6555 StdNamespace.get(Context.getExternalSource()));
6556}
6557
Douglas Gregor66992202010-06-29 17:53:46 +00006558/// \brief Retrieve the special "std" namespace, which may require us to
6559/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006560NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006561 if (!StdNamespace) {
6562 // The "std" namespace has not yet been defined, so build one implicitly.
6563 StdNamespace = NamespaceDecl::Create(Context,
6564 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006565 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006566 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006567 &PP.getIdentifierTable().get("std"),
6568 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006569 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006570 }
6571
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006572 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006573}
6574
Sebastian Redl395e04d2012-01-17 22:49:33 +00006575bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006576 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006577 "Looking for std::initializer_list outside of C++.");
6578
6579 // We're looking for implicit instantiations of
6580 // template <typename E> class std::initializer_list.
6581
6582 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6583 return false;
6584
Sebastian Redl84760e32012-01-17 22:49:58 +00006585 ClassTemplateDecl *Template = 0;
6586 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006587
Sebastian Redl84760e32012-01-17 22:49:58 +00006588 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006589
Sebastian Redl84760e32012-01-17 22:49:58 +00006590 ClassTemplateSpecializationDecl *Specialization =
6591 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6592 if (!Specialization)
6593 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006594
Sebastian Redl84760e32012-01-17 22:49:58 +00006595 Template = Specialization->getSpecializedTemplate();
6596 Arguments = Specialization->getTemplateArgs().data();
6597 } else if (const TemplateSpecializationType *TST =
6598 Ty->getAs<TemplateSpecializationType>()) {
6599 Template = dyn_cast_or_null<ClassTemplateDecl>(
6600 TST->getTemplateName().getAsTemplateDecl());
6601 Arguments = TST->getArgs();
6602 }
6603 if (!Template)
6604 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006605
6606 if (!StdInitializerList) {
6607 // Haven't recognized std::initializer_list yet, maybe this is it.
6608 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6609 if (TemplateClass->getIdentifier() !=
6610 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006611 !getStdNamespace()->InEnclosingNamespaceSetOf(
6612 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006613 return false;
6614 // This is a template called std::initializer_list, but is it the right
6615 // template?
6616 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006617 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006618 return false;
6619 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6620 return false;
6621
6622 // It's the right template.
6623 StdInitializerList = Template;
6624 }
6625
6626 if (Template != StdInitializerList)
6627 return false;
6628
6629 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006630 if (Element)
6631 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006632 return true;
6633}
6634
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006635static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6636 NamespaceDecl *Std = S.getStdNamespace();
6637 if (!Std) {
6638 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6639 return 0;
6640 }
6641
6642 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6643 Loc, Sema::LookupOrdinaryName);
6644 if (!S.LookupQualifiedName(Result, Std)) {
6645 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6646 return 0;
6647 }
6648 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6649 if (!Template) {
6650 Result.suppressDiagnostics();
6651 // We found something weird. Complain about the first thing we found.
6652 NamedDecl *Found = *Result.begin();
6653 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6654 return 0;
6655 }
6656
6657 // We found some template called std::initializer_list. Now verify that it's
6658 // correct.
6659 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006660 if (Params->getMinRequiredArguments() != 1 ||
6661 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006662 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6663 return 0;
6664 }
6665
6666 return Template;
6667}
6668
6669QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6670 if (!StdInitializerList) {
6671 StdInitializerList = LookupStdInitializerList(*this, Loc);
6672 if (!StdInitializerList)
6673 return QualType();
6674 }
6675
6676 TemplateArgumentListInfo Args(Loc, Loc);
6677 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6678 Context.getTrivialTypeSourceInfo(Element,
6679 Loc)));
6680 return Context.getCanonicalType(
6681 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6682}
6683
Sebastian Redl98d36062012-01-17 22:50:14 +00006684bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6685 // C++ [dcl.init.list]p2:
6686 // A constructor is an initializer-list constructor if its first parameter
6687 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6688 // std::initializer_list<E> for some type E, and either there are no other
6689 // parameters or else all other parameters have default arguments.
6690 if (Ctor->getNumParams() < 1 ||
6691 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6692 return false;
6693
6694 QualType ArgType = Ctor->getParamDecl(0)->getType();
6695 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6696 ArgType = RT->getPointeeType().getUnqualifiedType();
6697
6698 return isStdInitializerList(ArgType, 0);
6699}
6700
Douglas Gregor9172aa62011-03-26 22:25:30 +00006701/// \brief Determine whether a using statement is in a context where it will be
6702/// apply in all contexts.
6703static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6704 switch (CurContext->getDeclKind()) {
6705 case Decl::TranslationUnit:
6706 return true;
6707 case Decl::LinkageSpec:
6708 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6709 default:
6710 return false;
6711 }
6712}
6713
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006714namespace {
6715
6716// Callback to only accept typo corrections that are namespaces.
6717class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006718public:
6719 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6720 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006721 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006722 return false;
6723 }
6724};
6725
6726}
6727
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006728static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6729 CXXScopeSpec &SS,
6730 SourceLocation IdentLoc,
6731 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006732 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006733 R.clear();
6734 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006735 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006736 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006737 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006738 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6739 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006740 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006741 S.diagnoseTypo(Corrected,
6742 S.PDiag(diag::err_using_directive_member_suggest)
6743 << Ident << DC << DroppedSpecifier << SS.getRange(),
6744 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006745 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006746 S.diagnoseTypo(Corrected,
6747 S.PDiag(diag::err_using_directive_suggest) << Ident,
6748 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006749 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006750 R.addDecl(Corrected.getCorrectionDecl());
6751 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006752 }
6753 return false;
6754}
6755
John McCalld226f652010-08-21 09:40:31 +00006756Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006757 SourceLocation UsingLoc,
6758 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006759 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006760 SourceLocation IdentLoc,
6761 IdentifierInfo *NamespcName,
6762 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006763 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6764 assert(NamespcName && "Invalid NamespcName.");
6765 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006766
6767 // This can only happen along a recovery path.
6768 while (S->getFlags() & Scope::TemplateParamScope)
6769 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006770 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006771
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006772 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006773 NestedNameSpecifier *Qualifier = 0;
6774 if (SS.isSet())
6775 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6776
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006777 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006778 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6779 LookupParsedName(R, S, &SS);
6780 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006781 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006782
Douglas Gregor66992202010-06-29 17:53:46 +00006783 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006784 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006785 // Allow "using namespace std;" or "using namespace ::std;" even if
6786 // "std" hasn't been defined yet, for GCC compatibility.
6787 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6788 NamespcName->isStr("std")) {
6789 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006790 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006791 R.resolveKind();
6792 }
6793 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006794 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006795 }
6796
John McCallf36e02d2009-10-09 21:13:30 +00006797 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006798 NamedDecl *Named = R.getFoundDecl();
6799 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6800 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006801 // C++ [namespace.udir]p1:
6802 // A using-directive specifies that the names in the nominated
6803 // namespace can be used in the scope in which the
6804 // using-directive appears after the using-directive. During
6805 // unqualified name lookup (3.4.1), the names appear as if they
6806 // were declared in the nearest enclosing namespace which
6807 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006808 // namespace. [Note: in this context, "contains" means "contains
6809 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006810
6811 // Find enclosing context containing both using-directive and
6812 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006813 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006814 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6815 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6816 CommonAncestor = CommonAncestor->getParent();
6817
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006818 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006819 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006820 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006821
Douglas Gregor9172aa62011-03-26 22:25:30 +00006822 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006823 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006824 Diag(IdentLoc, diag::warn_using_directive_in_header);
6825 }
6826
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006827 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006828 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006829 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006830 }
6831
Richard Smith6b3d3e52013-02-20 19:22:51 +00006832 if (UDir)
6833 ProcessDeclAttributeList(S, UDir, AttrList);
6834
John McCalld226f652010-08-21 09:40:31 +00006835 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006836}
6837
6838void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006839 // If the scope has an associated entity and the using directive is at
6840 // namespace or translation unit scope, add the UsingDirectiveDecl into
6841 // its lookup structure so qualified name lookup can find it.
6842 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6843 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006844 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006845 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006846 // Otherwise, it is at block sope. The using-directives will affect lookup
6847 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006848 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006849}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006850
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006851
John McCalld226f652010-08-21 09:40:31 +00006852Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006853 AccessSpecifier AS,
6854 bool HasUsingKeyword,
6855 SourceLocation UsingLoc,
6856 CXXScopeSpec &SS,
6857 UnqualifiedId &Name,
6858 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006859 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006860 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006861 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006862
Douglas Gregor12c118a2009-11-04 16:30:06 +00006863 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006864 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006865 case UnqualifiedId::IK_Identifier:
6866 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006867 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006868 case UnqualifiedId::IK_ConversionFunctionId:
6869 break;
6870
6871 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006872 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006873 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006874 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006875 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006876 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006877 diag::err_using_decl_constructor)
6878 << SS.getRange();
6879
Richard Smith80ad52f2013-01-02 11:42:31 +00006880 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006881
John McCalld226f652010-08-21 09:40:31 +00006882 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006883
6884 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006885 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006886 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006887 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006888
6889 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006890 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006891 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006892 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006893 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006894
6895 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6896 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006897 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006898 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006899
Richard Smith07b0fdc2013-03-18 21:12:30 +00006900 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006901 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006902 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006903 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6904 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006905 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006906 }
6907
Douglas Gregor56c04582010-12-16 00:46:58 +00006908 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6909 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6910 return 0;
6911
John McCall9488ea12009-11-17 05:59:44 +00006912 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006913 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006914 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006915 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006916 if (UD)
6917 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006918
John McCalld226f652010-08-21 09:40:31 +00006919 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006920}
6921
Douglas Gregor09acc982010-07-07 23:08:52 +00006922/// \brief Determine whether a using declaration considers the given
6923/// declarations as "equivalent", e.g., if they are redeclarations of
6924/// the same entity or are both typedefs of the same type.
6925static bool
6926IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6927 bool &SuppressRedeclaration) {
6928 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6929 SuppressRedeclaration = false;
6930 return true;
6931 }
6932
Richard Smith162e1c12011-04-15 14:24:37 +00006933 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6934 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006935 SuppressRedeclaration = true;
6936 return Context.hasSameType(TD1->getUnderlyingType(),
6937 TD2->getUnderlyingType());
6938 }
6939
6940 return false;
6941}
6942
6943
John McCall9f54ad42009-12-10 09:41:52 +00006944/// Determines whether to create a using shadow decl for a particular
6945/// decl, given the set of decls existing prior to this using lookup.
6946bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6947 const LookupResult &Previous) {
6948 // Diagnose finding a decl which is not from a base class of the
6949 // current class. We do this now because there are cases where this
6950 // function will silently decide not to build a shadow decl, which
6951 // will pre-empt further diagnostics.
6952 //
6953 // We don't need to do this in C++0x because we do the check once on
6954 // the qualifier.
6955 //
6956 // FIXME: diagnose the following if we care enough:
6957 // struct A { int foo; };
6958 // struct B : A { using A::foo; };
6959 // template <class T> struct C : A {};
6960 // template <class T> struct D : C<T> { using B::foo; } // <---
6961 // This is invalid (during instantiation) in C++03 because B::foo
6962 // resolves to the using decl in B, which is not a base class of D<T>.
6963 // We can't diagnose it immediately because C<T> is an unknown
6964 // specialization. The UsingShadowDecl in D<T> then points directly
6965 // to A::foo, which will look well-formed when we instantiate.
6966 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006967 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006968 DeclContext *OrigDC = Orig->getDeclContext();
6969
6970 // Handle enums and anonymous structs.
6971 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6972 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6973 while (OrigRec->isAnonymousStructOrUnion())
6974 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6975
6976 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6977 if (OrigDC == CurContext) {
6978 Diag(Using->getLocation(),
6979 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006980 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006981 Diag(Orig->getLocation(), diag::note_using_decl_target);
6982 return true;
6983 }
6984
Douglas Gregordc355712011-02-25 00:36:19 +00006985 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006986 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006987 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006988 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006989 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006990 Diag(Orig->getLocation(), diag::note_using_decl_target);
6991 return true;
6992 }
6993 }
6994
6995 if (Previous.empty()) return false;
6996
6997 NamedDecl *Target = Orig;
6998 if (isa<UsingShadowDecl>(Target))
6999 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7000
John McCalld7533ec2009-12-11 02:33:26 +00007001 // If the target happens to be one of the previous declarations, we
7002 // don't have a conflict.
7003 //
7004 // FIXME: but we might be increasing its access, in which case we
7005 // should redeclare it.
7006 NamedDecl *NonTag = 0, *Tag = 0;
7007 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7008 I != E; ++I) {
7009 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00007010 bool Result;
7011 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
7012 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00007013
7014 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7015 }
7016
John McCall9f54ad42009-12-10 09:41:52 +00007017 if (Target->isFunctionOrFunctionTemplate()) {
7018 FunctionDecl *FD;
7019 if (isa<FunctionTemplateDecl>(Target))
7020 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7021 else
7022 FD = cast<FunctionDecl>(Target);
7023
7024 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007025 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007026 case Ovl_Overload:
7027 return false;
7028
7029 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007030 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007031 break;
7032
7033 // We found a decl with the exact signature.
7034 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007035 // If we're in a record, we want to hide the target, so we
7036 // return true (without a diagnostic) to tell the caller not to
7037 // build a shadow decl.
7038 if (CurContext->isRecord())
7039 return true;
7040
7041 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007042 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007043 break;
7044 }
7045
7046 Diag(Target->getLocation(), diag::note_using_decl_target);
7047 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7048 return true;
7049 }
7050
7051 // Target is not a function.
7052
John McCall9f54ad42009-12-10 09:41:52 +00007053 if (isa<TagDecl>(Target)) {
7054 // No conflict between a tag and a non-tag.
7055 if (!Tag) return false;
7056
John McCall41ce66f2009-12-10 19:51:03 +00007057 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007058 Diag(Target->getLocation(), diag::note_using_decl_target);
7059 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7060 return true;
7061 }
7062
7063 // No conflict between a tag and a non-tag.
7064 if (!NonTag) return false;
7065
John McCall41ce66f2009-12-10 19:51:03 +00007066 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007067 Diag(Target->getLocation(), diag::note_using_decl_target);
7068 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7069 return true;
7070}
7071
John McCall9488ea12009-11-17 05:59:44 +00007072/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007073UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007074 UsingDecl *UD,
7075 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00007076
7077 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007078 NamedDecl *Target = Orig;
7079 if (isa<UsingShadowDecl>(Target)) {
7080 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7081 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007082 }
7083
7084 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007085 = UsingShadowDecl::Create(Context, CurContext,
7086 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007087 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00007088
7089 Shadow->setAccess(UD->getAccess());
7090 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7091 Shadow->setInvalidDecl();
7092
John McCall9488ea12009-11-17 05:59:44 +00007093 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007094 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007095 else
John McCall604e7f12009-12-08 07:46:18 +00007096 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007097
John McCall604e7f12009-12-08 07:46:18 +00007098
John McCall9f54ad42009-12-10 09:41:52 +00007099 return Shadow;
7100}
John McCall604e7f12009-12-08 07:46:18 +00007101
John McCall9f54ad42009-12-10 09:41:52 +00007102/// Hides a using shadow declaration. This is required by the current
7103/// using-decl implementation when a resolvable using declaration in a
7104/// class is followed by a declaration which would hide or override
7105/// one or more of the using decl's targets; for example:
7106///
7107/// struct Base { void foo(int); };
7108/// struct Derived : Base {
7109/// using Base::foo;
7110/// void foo(int);
7111/// };
7112///
7113/// The governing language is C++03 [namespace.udecl]p12:
7114///
7115/// When a using-declaration brings names from a base class into a
7116/// derived class scope, member functions in the derived class
7117/// override and/or hide member functions with the same name and
7118/// parameter types in a base class (rather than conflicting).
7119///
7120/// There are two ways to implement this:
7121/// (1) optimistically create shadow decls when they're not hidden
7122/// by existing declarations, or
7123/// (2) don't create any shadow decls (or at least don't make them
7124/// visible) until we've fully parsed/instantiated the class.
7125/// The problem with (1) is that we might have to retroactively remove
7126/// a shadow decl, which requires several O(n) operations because the
7127/// decl structures are (very reasonably) not designed for removal.
7128/// (2) avoids this but is very fiddly and phase-dependent.
7129void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007130 if (Shadow->getDeclName().getNameKind() ==
7131 DeclarationName::CXXConversionFunctionName)
7132 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7133
John McCall9f54ad42009-12-10 09:41:52 +00007134 // Remove it from the DeclContext...
7135 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007136
John McCall9f54ad42009-12-10 09:41:52 +00007137 // ...and the scope, if applicable...
7138 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007139 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007140 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007141 }
7142
John McCall9f54ad42009-12-10 09:41:52 +00007143 // ...and the using decl.
7144 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7145
7146 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007147 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007148}
7149
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007150namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007151class UsingValidatorCCC : public CorrectionCandidateCallback {
7152public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007153 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7154 : HasTypenameKeyword(HasTypenameKeyword),
7155 IsInstantiation(IsInstantiation) {}
7156
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007157 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7158 NamedDecl *ND = Candidate.getCorrectionDecl();
7159
7160 // Keywords are not valid here.
7161 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007162 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007163
7164 // Completely unqualified names are invalid for a 'using' declaration.
7165 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7166 return false;
7167
7168 if (isa<TypeDecl>(ND))
7169 return HasTypenameKeyword || !IsInstantiation;
7170
7171 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007172 }
7173
7174private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007175 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007176 bool IsInstantiation;
7177};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007178} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007179
John McCall7ba107a2009-11-18 02:36:19 +00007180/// Builds a using declaration.
7181///
7182/// \param IsInstantiation - Whether this call arises from an
7183/// instantiation of an unresolved using declaration. We treat
7184/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007185NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7186 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007187 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007188 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007189 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007190 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007191 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007192 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007193 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007194 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007195 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007196
Anders Carlsson550b14b2009-08-28 05:49:21 +00007197 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007198
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007199 if (SS.isEmpty()) {
7200 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007201 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007202 }
Mike Stump1eb44332009-09-09 15:08:12 +00007203
John McCall9f54ad42009-12-10 09:41:52 +00007204 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007205 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007206 ForRedeclaration);
7207 Previous.setHideTags(false);
7208 if (S) {
7209 LookupName(Previous, S);
7210
7211 // It is really dumb that we have to do this.
7212 LookupResult::Filter F = Previous.makeFilter();
7213 while (F.hasNext()) {
7214 NamedDecl *D = F.next();
7215 if (!isDeclInScope(D, CurContext, S))
7216 F.erase();
7217 }
7218 F.done();
7219 } else {
7220 assert(IsInstantiation && "no scope in non-instantiation");
7221 assert(CurContext->isRecord() && "scope not record in instantiation");
7222 LookupQualifiedName(Previous, CurContext);
7223 }
7224
John McCall9f54ad42009-12-10 09:41:52 +00007225 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007226 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7227 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007228 return 0;
7229
7230 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007231 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7232 return 0;
7233
John McCallaf8e6ed2009-11-12 03:15:40 +00007234 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007235 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007236 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007237 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007238 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007239 // FIXME: not all declaration name kinds are legal here
7240 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7241 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007242 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007243 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007244 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007245 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7246 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007247 }
John McCalled976492009-12-04 22:46:56 +00007248 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007249 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007250 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007251 }
John McCalled976492009-12-04 22:46:56 +00007252 D->setAccess(AS);
7253 CurContext->addDecl(D);
7254
7255 if (!LookupContext) return D;
7256 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007257
John McCall77bb1aa2010-05-01 00:40:08 +00007258 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007259 UD->setInvalidDecl();
7260 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007261 }
7262
Richard Smithc5a89a12012-04-02 01:30:27 +00007263 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007264 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007265 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007266 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007267 return UD;
7268 }
7269
7270 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007271
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007272 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007273
John McCall604e7f12009-12-08 07:46:18 +00007274 // Unlike most lookups, we don't always want to hide tag
7275 // declarations: tag names are visible through the using declaration
7276 // even if hidden by ordinary names, *except* in a dependent context
7277 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007278 if (!IsInstantiation)
7279 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007280
John McCallb9abd8722012-04-07 03:04:20 +00007281 // For the purposes of this lookup, we have a base object type
7282 // equal to that of the current context.
7283 if (CurContext->isRecord()) {
7284 R.setBaseObjectType(
7285 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7286 }
7287
John McCalla24dc2e2009-11-17 02:14:36 +00007288 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007289
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007290 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007291 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007292 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007293 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7294 R.getLookupKind(), S, &SS, CCC)){
7295 // We reject any correction for which ND would be NULL.
7296 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007297 R.setLookupName(Corrected.getCorrection());
7298 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007299 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007300 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007301 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7302 << NameInfo.getName() << LookupContext << 0
7303 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007304 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007305 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007306 << NameInfo.getName() << LookupContext << SS.getRange();
7307 UD->setInvalidDecl();
7308 return UD;
7309 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007310 }
7311
John McCalled976492009-12-04 22:46:56 +00007312 if (R.isAmbiguous()) {
7313 UD->setInvalidDecl();
7314 return UD;
7315 }
Mike Stump1eb44332009-09-09 15:08:12 +00007316
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007317 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007318 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007319 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007320 Diag(IdentLoc, diag::err_using_typename_non_type);
7321 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7322 Diag((*I)->getUnderlyingDecl()->getLocation(),
7323 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007324 UD->setInvalidDecl();
7325 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007326 }
7327 } else {
7328 // If we asked for a non-typename and we got a type, error out,
7329 // but only if this is an instantiation of an unresolved using
7330 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007331 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007332 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7333 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007334 UD->setInvalidDecl();
7335 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007336 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007337 }
7338
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007339 // C++0x N2914 [namespace.udecl]p6:
7340 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007341 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007342 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7343 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007344 UD->setInvalidDecl();
7345 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007346 }
Mike Stump1eb44332009-09-09 15:08:12 +00007347
John McCall9f54ad42009-12-10 09:41:52 +00007348 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7349 if (!CheckUsingShadowDecl(UD, *I, Previous))
7350 BuildUsingShadowDecl(S, UD, *I);
7351 }
John McCall9488ea12009-11-17 05:59:44 +00007352
7353 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007354}
7355
Sebastian Redlf677ea32011-02-05 19:23:19 +00007356/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007357bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007358 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007359
Douglas Gregordc355712011-02-25 00:36:19 +00007360 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007361 assert(SourceType &&
7362 "Using decl naming constructor doesn't have type in scope spec.");
7363 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7364
7365 // Check whether the named type is a direct base class.
7366 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7367 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7368 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7369 BaseIt != BaseE; ++BaseIt) {
7370 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7371 if (CanonicalSourceType == BaseType)
7372 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007373 if (BaseIt->getType()->isDependentType())
7374 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007375 }
7376
7377 if (BaseIt == BaseE) {
7378 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007379 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007380 diag::err_using_decl_constructor_not_in_direct_base)
7381 << UD->getNameInfo().getSourceRange()
7382 << QualType(SourceType, 0) << TargetClass;
7383 return true;
7384 }
7385
Richard Smithc5a89a12012-04-02 01:30:27 +00007386 if (!CurContext->isDependentContext())
7387 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007388
7389 return false;
7390}
7391
John McCall9f54ad42009-12-10 09:41:52 +00007392/// Checks that the given using declaration is not an invalid
7393/// redeclaration. Note that this is checking only for the using decl
7394/// itself, not for any ill-formedness among the UsingShadowDecls.
7395bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007396 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007397 const CXXScopeSpec &SS,
7398 SourceLocation NameLoc,
7399 const LookupResult &Prev) {
7400 // C++03 [namespace.udecl]p8:
7401 // C++0x [namespace.udecl]p10:
7402 // A using-declaration is a declaration and can therefore be used
7403 // repeatedly where (and only where) multiple declarations are
7404 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007405 //
John McCall8a726212010-11-29 18:01:58 +00007406 // That's in non-member contexts.
7407 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007408 return false;
7409
7410 NestedNameSpecifier *Qual
7411 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7412
7413 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7414 NamedDecl *D = *I;
7415
7416 bool DTypename;
7417 NestedNameSpecifier *DQual;
7418 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007419 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007420 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007421 } else if (UnresolvedUsingValueDecl *UD
7422 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7423 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007424 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007425 } else if (UnresolvedUsingTypenameDecl *UD
7426 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7427 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007428 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007429 } else continue;
7430
7431 // using decls differ if one says 'typename' and the other doesn't.
7432 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007433 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007434
7435 // using decls differ if they name different scopes (but note that
7436 // template instantiation can cause this check to trigger when it
7437 // didn't before instantiation).
7438 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7439 Context.getCanonicalNestedNameSpecifier(DQual))
7440 continue;
7441
7442 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007443 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007444 return true;
7445 }
7446
7447 return false;
7448}
7449
John McCall604e7f12009-12-08 07:46:18 +00007450
John McCalled976492009-12-04 22:46:56 +00007451/// Checks that the given nested-name qualifier used in a using decl
7452/// in the current context is appropriately related to the current
7453/// scope. If an error is found, diagnoses it and returns true.
7454bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7455 const CXXScopeSpec &SS,
7456 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007457 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007458
John McCall604e7f12009-12-08 07:46:18 +00007459 if (!CurContext->isRecord()) {
7460 // C++03 [namespace.udecl]p3:
7461 // C++0x [namespace.udecl]p8:
7462 // A using-declaration for a class member shall be a member-declaration.
7463
7464 // If we weren't able to compute a valid scope, it must be a
7465 // dependent class scope.
7466 if (!NamedContext || NamedContext->isRecord()) {
7467 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7468 << SS.getRange();
7469 return true;
7470 }
7471
7472 // Otherwise, everything is known to be fine.
7473 return false;
7474 }
7475
7476 // The current scope is a record.
7477
7478 // If the named context is dependent, we can't decide much.
7479 if (!NamedContext) {
7480 // FIXME: in C++0x, we can diagnose if we can prove that the
7481 // nested-name-specifier does not refer to a base class, which is
7482 // still possible in some cases.
7483
7484 // Otherwise we have to conservatively report that things might be
7485 // okay.
7486 return false;
7487 }
7488
7489 if (!NamedContext->isRecord()) {
7490 // Ideally this would point at the last name in the specifier,
7491 // but we don't have that level of source info.
7492 Diag(SS.getRange().getBegin(),
7493 diag::err_using_decl_nested_name_specifier_is_not_class)
7494 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7495 return true;
7496 }
7497
Douglas Gregor6fb07292010-12-21 07:41:49 +00007498 if (!NamedContext->isDependentContext() &&
7499 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7500 return true;
7501
Richard Smith80ad52f2013-01-02 11:42:31 +00007502 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007503 // C++0x [namespace.udecl]p3:
7504 // In a using-declaration used as a member-declaration, the
7505 // nested-name-specifier shall name a base class of the class
7506 // being defined.
7507
7508 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7509 cast<CXXRecordDecl>(NamedContext))) {
7510 if (CurContext == NamedContext) {
7511 Diag(NameLoc,
7512 diag::err_using_decl_nested_name_specifier_is_current_class)
7513 << SS.getRange();
7514 return true;
7515 }
7516
7517 Diag(SS.getRange().getBegin(),
7518 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7519 << (NestedNameSpecifier*) SS.getScopeRep()
7520 << cast<CXXRecordDecl>(CurContext)
7521 << SS.getRange();
7522 return true;
7523 }
7524
7525 return false;
7526 }
7527
7528 // C++03 [namespace.udecl]p4:
7529 // A using-declaration used as a member-declaration shall refer
7530 // to a member of a base class of the class being defined [etc.].
7531
7532 // Salient point: SS doesn't have to name a base class as long as
7533 // lookup only finds members from base classes. Therefore we can
7534 // diagnose here only if we can prove that that can't happen,
7535 // i.e. if the class hierarchies provably don't intersect.
7536
7537 // TODO: it would be nice if "definitely valid" results were cached
7538 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7539 // need to be repeated.
7540
7541 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007542 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007543
7544 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7545 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7546 Data->Bases.insert(Base);
7547 return true;
7548 }
7549
7550 bool hasDependentBases(const CXXRecordDecl *Class) {
7551 return !Class->forallBases(collect, this);
7552 }
7553
7554 /// Returns true if the base is dependent or is one of the
7555 /// accumulated base classes.
7556 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7557 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7558 return !Data->Bases.count(Base);
7559 }
7560
7561 bool mightShareBases(const CXXRecordDecl *Class) {
7562 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7563 }
7564 };
7565
7566 UserData Data;
7567
7568 // Returns false if we find a dependent base.
7569 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7570 return false;
7571
7572 // Returns false if the class has a dependent base or if it or one
7573 // of its bases is present in the base set of the current context.
7574 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7575 return false;
7576
7577 Diag(SS.getRange().getBegin(),
7578 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7579 << (NestedNameSpecifier*) SS.getScopeRep()
7580 << cast<CXXRecordDecl>(CurContext)
7581 << SS.getRange();
7582
7583 return true;
John McCalled976492009-12-04 22:46:56 +00007584}
7585
Richard Smith162e1c12011-04-15 14:24:37 +00007586Decl *Sema::ActOnAliasDeclaration(Scope *S,
7587 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007588 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007589 SourceLocation UsingLoc,
7590 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007591 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007592 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007593 // Skip up to the relevant declaration scope.
7594 while (S->getFlags() & Scope::TemplateParamScope)
7595 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007596 assert((S->getFlags() & Scope::DeclScope) &&
7597 "got alias-declaration outside of declaration scope");
7598
7599 if (Type.isInvalid())
7600 return 0;
7601
7602 bool Invalid = false;
7603 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7604 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007605 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007606
7607 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7608 return 0;
7609
7610 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007611 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007612 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007613 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7614 TInfo->getTypeLoc().getBeginLoc());
7615 }
Richard Smith162e1c12011-04-15 14:24:37 +00007616
7617 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7618 LookupName(Previous, S);
7619
7620 // Warn about shadowing the name of a template parameter.
7621 if (Previous.isSingleResult() &&
7622 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007623 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007624 Previous.clear();
7625 }
7626
7627 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7628 "name in alias declaration must be an identifier");
7629 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7630 Name.StartLocation,
7631 Name.Identifier, TInfo);
7632
7633 NewTD->setAccess(AS);
7634
7635 if (Invalid)
7636 NewTD->setInvalidDecl();
7637
Richard Smith6b3d3e52013-02-20 19:22:51 +00007638 ProcessDeclAttributeList(S, NewTD, AttrList);
7639
Richard Smith3e4c6c42011-05-05 21:57:07 +00007640 CheckTypedefForVariablyModifiedType(S, NewTD);
7641 Invalid |= NewTD->isInvalidDecl();
7642
Richard Smith162e1c12011-04-15 14:24:37 +00007643 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007644
7645 NamedDecl *NewND;
7646 if (TemplateParamLists.size()) {
7647 TypeAliasTemplateDecl *OldDecl = 0;
7648 TemplateParameterList *OldTemplateParams = 0;
7649
7650 if (TemplateParamLists.size() != 1) {
7651 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007652 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7653 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007654 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007655 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007656
7657 // Only consider previous declarations in the same scope.
7658 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7659 /*ExplicitInstantiationOrSpecialization*/false);
7660 if (!Previous.empty()) {
7661 Redeclaration = true;
7662
7663 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7664 if (!OldDecl && !Invalid) {
7665 Diag(UsingLoc, diag::err_redefinition_different_kind)
7666 << Name.Identifier;
7667
7668 NamedDecl *OldD = Previous.getRepresentativeDecl();
7669 if (OldD->getLocation().isValid())
7670 Diag(OldD->getLocation(), diag::note_previous_definition);
7671
7672 Invalid = true;
7673 }
7674
7675 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7676 if (TemplateParameterListsAreEqual(TemplateParams,
7677 OldDecl->getTemplateParameters(),
7678 /*Complain=*/true,
7679 TPL_TemplateMatch))
7680 OldTemplateParams = OldDecl->getTemplateParameters();
7681 else
7682 Invalid = true;
7683
7684 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7685 if (!Invalid &&
7686 !Context.hasSameType(OldTD->getUnderlyingType(),
7687 NewTD->getUnderlyingType())) {
7688 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7689 // but we can't reasonably accept it.
7690 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7691 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7692 if (OldTD->getLocation().isValid())
7693 Diag(OldTD->getLocation(), diag::note_previous_definition);
7694 Invalid = true;
7695 }
7696 }
7697 }
7698
7699 // Merge any previous default template arguments into our parameters,
7700 // and check the parameter list.
7701 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7702 TPC_TypeAliasTemplate))
7703 return 0;
7704
7705 TypeAliasTemplateDecl *NewDecl =
7706 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7707 Name.Identifier, TemplateParams,
7708 NewTD);
7709
7710 NewDecl->setAccess(AS);
7711
7712 if (Invalid)
7713 NewDecl->setInvalidDecl();
7714 else if (OldDecl)
7715 NewDecl->setPreviousDeclaration(OldDecl);
7716
7717 NewND = NewDecl;
7718 } else {
7719 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7720 NewND = NewTD;
7721 }
Richard Smith162e1c12011-04-15 14:24:37 +00007722
7723 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007724 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007725
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007726 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007727 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007728}
7729
John McCalld226f652010-08-21 09:40:31 +00007730Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007731 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007732 SourceLocation AliasLoc,
7733 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007734 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007735 SourceLocation IdentLoc,
7736 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007737
Anders Carlsson81c85c42009-03-28 23:53:49 +00007738 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007739 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7740 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007741
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007742 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007743 NamedDecl *PrevDecl
7744 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7745 ForRedeclaration);
7746 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7747 PrevDecl = 0;
7748
7749 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007750 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007751 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007752 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007753 // FIXME: At some point, we'll want to create the (redundant)
7754 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007755 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007756 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007757 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007758 }
Mike Stump1eb44332009-09-09 15:08:12 +00007759
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007760 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7761 diag::err_redefinition_different_kind;
7762 Diag(AliasLoc, DiagID) << Alias;
7763 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007764 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007765 }
7766
John McCalla24dc2e2009-11-17 02:14:36 +00007767 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007768 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007769
John McCallf36e02d2009-10-09 21:13:30 +00007770 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007771 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007772 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007773 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007774 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007775 }
Mike Stump1eb44332009-09-09 15:08:12 +00007776
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007777 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007778 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007779 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007780 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007781
John McCall3dbd3d52010-02-16 06:53:13 +00007782 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007783 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007784}
7785
Sean Hunt001cad92011-05-10 00:49:42 +00007786Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007787Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7788 CXXMethodDecl *MD) {
7789 CXXRecordDecl *ClassDecl = MD->getParent();
7790
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007791 // C++ [except.spec]p14:
7792 // An implicitly declared special member function (Clause 12) shall have an
7793 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007794 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007795 if (ClassDecl->isInvalidDecl())
7796 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007797
Sebastian Redl60618fa2011-03-12 11:50:43 +00007798 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007799 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7800 BEnd = ClassDecl->bases_end();
7801 B != BEnd; ++B) {
7802 if (B->isVirtual()) // Handled below.
7803 continue;
7804
Douglas Gregor18274032010-07-03 00:47:00 +00007805 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7806 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007807 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7808 // If this is a deleted function, add it anyway. This might be conformant
7809 // with the standard. This might not. I'm not sure. It might not matter.
7810 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007811 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007812 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007813 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007814
7815 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007816 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7817 BEnd = ClassDecl->vbases_end();
7818 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007819 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7820 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007821 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7822 // If this is a deleted function, add it anyway. This might be conformant
7823 // with the standard. This might not. I'm not sure. It might not matter.
7824 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007825 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007826 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007827 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007828
7829 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007830 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7831 FEnd = ClassDecl->field_end();
7832 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007833 if (F->hasInClassInitializer()) {
7834 if (Expr *E = F->getInClassInitializer())
7835 ExceptSpec.CalledExpr(E);
7836 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007837 // DR1351:
7838 // If the brace-or-equal-initializer of a non-static data member
7839 // invokes a defaulted default constructor of its class or of an
7840 // enclosing class in a potentially evaluated subexpression, the
7841 // program is ill-formed.
7842 //
7843 // This resolution is unworkable: the exception specification of the
7844 // default constructor can be needed in an unevaluated context, in
7845 // particular, in the operand of a noexcept-expression, and we can be
7846 // unable to compute an exception specification for an enclosed class.
7847 //
7848 // We do not allow an in-class initializer to require the evaluation
7849 // of the exception specification for any in-class initializer whose
7850 // definition is not lexically complete.
7851 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007852 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007853 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007854 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7855 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7856 // If this is a deleted function, add it anyway. This might be conformant
7857 // with the standard. This might not. I'm not sure. It might not matter.
7858 // In particular, the problem is that this function never gets called. It
7859 // might just be ill-formed because this function attempts to refer to
7860 // a deleted function here.
7861 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007862 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007863 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007864 }
John McCalle23cf432010-12-14 08:05:40 +00007865
Sean Hunt001cad92011-05-10 00:49:42 +00007866 return ExceptSpec;
7867}
7868
Richard Smith07b0fdc2013-03-18 21:12:30 +00007869Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007870Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7871 CXXRecordDecl *ClassDecl = CD->getParent();
7872
7873 // C++ [except.spec]p14:
7874 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007875 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007876 if (ClassDecl->isInvalidDecl())
7877 return ExceptSpec;
7878
7879 // Inherited constructor.
7880 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7881 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7882 // FIXME: Copying or moving the parameters could add extra exceptions to the
7883 // set, as could the default arguments for the inherited constructor. This
7884 // will be addressed when we implement the resolution of core issue 1351.
7885 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7886
7887 // Direct base-class constructors.
7888 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7889 BEnd = ClassDecl->bases_end();
7890 B != BEnd; ++B) {
7891 if (B->isVirtual()) // Handled below.
7892 continue;
7893
7894 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7895 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7896 if (BaseClassDecl == InheritedDecl)
7897 continue;
7898 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7899 if (Constructor)
7900 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7901 }
7902 }
7903
7904 // Virtual base-class constructors.
7905 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7906 BEnd = ClassDecl->vbases_end();
7907 B != BEnd; ++B) {
7908 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7909 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7910 if (BaseClassDecl == InheritedDecl)
7911 continue;
7912 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7913 if (Constructor)
7914 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7915 }
7916 }
7917
7918 // Field constructors.
7919 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7920 FEnd = ClassDecl->field_end();
7921 F != FEnd; ++F) {
7922 if (F->hasInClassInitializer()) {
7923 if (Expr *E = F->getInClassInitializer())
7924 ExceptSpec.CalledExpr(E);
7925 else if (!F->isInvalidDecl())
7926 Diag(CD->getLocation(),
7927 diag::err_in_class_initializer_references_def_ctor) << CD;
7928 } else if (const RecordType *RecordTy
7929 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7930 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7931 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7932 if (Constructor)
7933 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7934 }
7935 }
7936
Richard Smith07b0fdc2013-03-18 21:12:30 +00007937 return ExceptSpec;
7938}
7939
Richard Smithafb49182012-11-29 01:34:07 +00007940namespace {
7941/// RAII object to register a special member as being currently declared.
7942struct DeclaringSpecialMember {
7943 Sema &S;
7944 Sema::SpecialMemberDecl D;
7945 bool WasAlreadyBeingDeclared;
7946
7947 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7948 : S(S), D(RD, CSM) {
7949 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7950 if (WasAlreadyBeingDeclared)
7951 // This almost never happens, but if it does, ensure that our cache
7952 // doesn't contain a stale result.
7953 S.SpecialMemberCache.clear();
7954
7955 // FIXME: Register a note to be produced if we encounter an error while
7956 // declaring the special member.
7957 }
7958 ~DeclaringSpecialMember() {
7959 if (!WasAlreadyBeingDeclared)
7960 S.SpecialMembersBeingDeclared.erase(D);
7961 }
7962
7963 /// \brief Are we already trying to declare this special member?
7964 bool isAlreadyBeingDeclared() const {
7965 return WasAlreadyBeingDeclared;
7966 }
7967};
7968}
7969
Sean Hunt001cad92011-05-10 00:49:42 +00007970CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7971 CXXRecordDecl *ClassDecl) {
7972 // C++ [class.ctor]p5:
7973 // A default constructor for a class X is a constructor of class X
7974 // that can be called without an argument. If there is no
7975 // user-declared constructor for class X, a default constructor is
7976 // implicitly declared. An implicitly-declared default constructor
7977 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007978 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007979 "Should not build implicit default constructor!");
7980
Richard Smithafb49182012-11-29 01:34:07 +00007981 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7982 if (DSM.isAlreadyBeingDeclared())
7983 return 0;
7984
Richard Smith7756afa2012-06-10 05:43:50 +00007985 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7986 CXXDefaultConstructor,
7987 false);
7988
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007989 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007990 CanQualType ClassType
7991 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007992 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007993 DeclarationName Name
7994 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007995 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007996 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007997 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007998 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007999 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008000 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008001 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008002 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008003
8004 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008005 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008006 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008007
Richard Smithbc2a35d2012-12-08 08:32:28 +00008008 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8009 // constructors is easy to compute.
8010 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8011
8012 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008013 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008014
Douglas Gregor18274032010-07-03 00:47:00 +00008015 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008016 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008017
Douglas Gregor23c94db2010-07-02 17:43:08 +00008018 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008019 PushOnScopeChains(DefaultCon, S, false);
8020 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008021
Douglas Gregor32df23e2010-07-01 22:02:46 +00008022 return DefaultCon;
8023}
8024
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008025void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8026 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008027 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008028 !Constructor->doesThisDeclarationHaveABody() &&
8029 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008030 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008031
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008032 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008033 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008034
Eli Friedman9a14db32012-10-18 20:14:08 +00008035 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008036 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008037 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008038 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008039 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008040 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008041 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008042 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008043 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008044
8045 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008046 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008047
Eli Friedman86164e82013-09-05 00:02:25 +00008048 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008049 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008050
8051 if (ASTMutationListener *L = getASTMutationListener()) {
8052 L->CompletedImplicitDefinition(Constructor);
8053 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008054}
8055
Richard Smith7a614d82011-06-11 17:19:42 +00008056void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00008057 // Check that any explicitly-defaulted methods have exception specifications
8058 // compatible with their implicit exception specifications.
8059 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008060}
8061
Richard Smith4841ca52013-04-10 05:48:59 +00008062namespace {
8063/// Information on inheriting constructors to declare.
8064class InheritingConstructorInfo {
8065public:
8066 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8067 : SemaRef(SemaRef), Derived(Derived) {
8068 // Mark the constructors that we already have in the derived class.
8069 //
8070 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8071 // unless there is a user-declared constructor with the same signature in
8072 // the class where the using-declaration appears.
8073 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8074 }
8075
8076 void inheritAll(CXXRecordDecl *RD) {
8077 visitAll(RD, &InheritingConstructorInfo::inherit);
8078 }
8079
8080private:
8081 /// Information about an inheriting constructor.
8082 struct InheritingConstructor {
8083 InheritingConstructor()
8084 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8085
8086 /// If \c true, a constructor with this signature is already declared
8087 /// in the derived class.
8088 bool DeclaredInDerived;
8089
8090 /// The constructor which is inherited.
8091 const CXXConstructorDecl *BaseCtor;
8092
8093 /// The derived constructor we declared.
8094 CXXConstructorDecl *DerivedCtor;
8095 };
8096
8097 /// Inheriting constructors with a given canonical type. There can be at
8098 /// most one such non-template constructor, and any number of templated
8099 /// constructors.
8100 struct InheritingConstructorsForType {
8101 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008102 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8103 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008104
8105 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8106 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8107 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8108 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8109 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8110 false, S.TPL_TemplateMatch))
8111 return Templates[I].second;
8112 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8113 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008114 }
Richard Smith4841ca52013-04-10 05:48:59 +00008115
8116 return NonTemplate;
8117 }
8118 };
8119
8120 /// Get or create the inheriting constructor record for a constructor.
8121 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8122 QualType CtorType) {
8123 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8124 .getEntry(SemaRef, Ctor);
8125 }
8126
8127 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8128
8129 /// Process all constructors for a class.
8130 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8131 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8132 CtorE = RD->ctor_end();
8133 CtorIt != CtorE; ++CtorIt)
8134 (this->*Callback)(*CtorIt);
8135 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8136 I(RD->decls_begin()), E(RD->decls_end());
8137 I != E; ++I) {
8138 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8139 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8140 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008141 }
8142 }
Richard Smith4841ca52013-04-10 05:48:59 +00008143
8144 /// Note that a constructor (or constructor template) was declared in Derived.
8145 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8146 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8147 }
8148
8149 /// Inherit a single constructor.
8150 void inherit(const CXXConstructorDecl *Ctor) {
8151 const FunctionProtoType *CtorType =
8152 Ctor->getType()->castAs<FunctionProtoType>();
8153 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8154 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8155
8156 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8157
8158 // Core issue (no number yet): the ellipsis is always discarded.
8159 if (EPI.Variadic) {
8160 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8161 SemaRef.Diag(Ctor->getLocation(),
8162 diag::note_using_decl_constructor_ellipsis);
8163 EPI.Variadic = false;
8164 }
8165
8166 // Declare a constructor for each number of parameters.
8167 //
8168 // C++11 [class.inhctor]p1:
8169 // The candidate set of inherited constructors from the class X named in
8170 // the using-declaration consists of [... modulo defects ...] for each
8171 // constructor or constructor template of X, the set of constructors or
8172 // constructor templates that results from omitting any ellipsis parameter
8173 // specification and successively omitting parameters with a default
8174 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008175 unsigned MinParams = minParamsToInherit(Ctor);
8176 unsigned Params = Ctor->getNumParams();
8177 if (Params >= MinParams) {
8178 do
8179 declareCtor(UsingLoc, Ctor,
8180 SemaRef.Context.getFunctionType(
8181 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8182 while (Params > MinParams &&
8183 Ctor->getParamDecl(--Params)->hasDefaultArg());
8184 }
Richard Smith4841ca52013-04-10 05:48:59 +00008185 }
8186
8187 /// Find the using-declaration which specified that we should inherit the
8188 /// constructors of \p Base.
8189 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8190 // No fancy lookup required; just look for the base constructor name
8191 // directly within the derived class.
8192 ASTContext &Context = SemaRef.Context;
8193 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8194 Context.getCanonicalType(Context.getRecordType(Base)));
8195 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8196 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8197 }
8198
8199 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8200 // C++11 [class.inhctor]p3:
8201 // [F]or each constructor template in the candidate set of inherited
8202 // constructors, a constructor template is implicitly declared
8203 if (Ctor->getDescribedFunctionTemplate())
8204 return 0;
8205
8206 // For each non-template constructor in the candidate set of inherited
8207 // constructors other than a constructor having no parameters or a
8208 // copy/move constructor having a single parameter, a constructor is
8209 // implicitly declared [...]
8210 if (Ctor->getNumParams() == 0)
8211 return 1;
8212 if (Ctor->isCopyOrMoveConstructor())
8213 return 2;
8214
8215 // Per discussion on core reflector, never inherit a constructor which
8216 // would become a default, copy, or move constructor of Derived either.
8217 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8218 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8219 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8220 }
8221
8222 /// Declare a single inheriting constructor, inheriting the specified
8223 /// constructor, with the given type.
8224 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8225 QualType DerivedType) {
8226 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8227
8228 // C++11 [class.inhctor]p3:
8229 // ... a constructor is implicitly declared with the same constructor
8230 // characteristics unless there is a user-declared constructor with
8231 // the same signature in the class where the using-declaration appears
8232 if (Entry.DeclaredInDerived)
8233 return;
8234
8235 // C++11 [class.inhctor]p7:
8236 // If two using-declarations declare inheriting constructors with the
8237 // same signature, the program is ill-formed
8238 if (Entry.DerivedCtor) {
8239 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8240 // Only diagnose this once per constructor.
8241 if (Entry.DerivedCtor->isInvalidDecl())
8242 return;
8243 Entry.DerivedCtor->setInvalidDecl();
8244
8245 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8246 SemaRef.Diag(BaseCtor->getLocation(),
8247 diag::note_using_decl_constructor_conflict_current_ctor);
8248 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8249 diag::note_using_decl_constructor_conflict_previous_ctor);
8250 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8251 diag::note_using_decl_constructor_conflict_previous_using);
8252 } else {
8253 // Core issue (no number): if the same inheriting constructor is
8254 // produced by multiple base class constructors from the same base
8255 // class, the inheriting constructor is defined as deleted.
8256 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8257 }
8258
8259 return;
8260 }
8261
8262 ASTContext &Context = SemaRef.Context;
8263 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8264 Context.getCanonicalType(Context.getRecordType(Derived)));
8265 DeclarationNameInfo NameInfo(Name, UsingLoc);
8266
8267 TemplateParameterList *TemplateParams = 0;
8268 if (const FunctionTemplateDecl *FTD =
8269 BaseCtor->getDescribedFunctionTemplate()) {
8270 TemplateParams = FTD->getTemplateParameters();
8271 // We're reusing template parameters from a different DeclContext. This
8272 // is questionable at best, but works out because the template depth in
8273 // both places is guaranteed to be 0.
8274 // FIXME: Rebuild the template parameters in the new context, and
8275 // transform the function type to refer to them.
8276 }
8277
8278 // Build type source info pointing at the using-declaration. This is
8279 // required by template instantiation.
8280 TypeSourceInfo *TInfo =
8281 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8282 FunctionProtoTypeLoc ProtoLoc =
8283 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8284
8285 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8286 Context, Derived, UsingLoc, NameInfo, DerivedType,
8287 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8288 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8289
8290 // Build an unevaluated exception specification for this constructor.
8291 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8292 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8293 EPI.ExceptionSpecType = EST_Unevaluated;
8294 EPI.ExceptionSpecDecl = DerivedCtor;
8295 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8296 FPT->getArgTypes(), EPI));
8297
8298 // Build the parameter declarations.
8299 SmallVector<ParmVarDecl *, 16> ParamDecls;
8300 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8301 TypeSourceInfo *TInfo =
8302 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8303 ParmVarDecl *PD = ParmVarDecl::Create(
8304 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8305 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8306 PD->setScopeInfo(0, I);
8307 PD->setImplicit();
8308 ParamDecls.push_back(PD);
8309 ProtoLoc.setArg(I, PD);
8310 }
8311
8312 // Set up the new constructor.
8313 DerivedCtor->setAccess(BaseCtor->getAccess());
8314 DerivedCtor->setParams(ParamDecls);
8315 DerivedCtor->setInheritedConstructor(BaseCtor);
8316 if (BaseCtor->isDeleted())
8317 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8318
8319 // If this is a constructor template, build the template declaration.
8320 if (TemplateParams) {
8321 FunctionTemplateDecl *DerivedTemplate =
8322 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8323 TemplateParams, DerivedCtor);
8324 DerivedTemplate->setAccess(BaseCtor->getAccess());
8325 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8326 Derived->addDecl(DerivedTemplate);
8327 } else {
8328 Derived->addDecl(DerivedCtor);
8329 }
8330
8331 Entry.BaseCtor = BaseCtor;
8332 Entry.DerivedCtor = DerivedCtor;
8333 }
8334
8335 Sema &SemaRef;
8336 CXXRecordDecl *Derived;
8337 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8338 MapType Map;
8339};
8340}
8341
8342void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8343 // Defer declaring the inheriting constructors until the class is
8344 // instantiated.
8345 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008346 return;
8347
Richard Smith4841ca52013-04-10 05:48:59 +00008348 // Find base classes from which we might inherit constructors.
8349 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8350 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8351 BaseE = ClassDecl->bases_end();
8352 BaseIt != BaseE; ++BaseIt)
8353 if (BaseIt->getInheritConstructors())
8354 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008355
Richard Smith4841ca52013-04-10 05:48:59 +00008356 // Go no further if we're not inheriting any constructors.
8357 if (InheritedBases.empty())
8358 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008359
Richard Smith4841ca52013-04-10 05:48:59 +00008360 // Declare the inherited constructors.
8361 InheritingConstructorInfo ICI(*this, ClassDecl);
8362 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8363 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008364}
8365
Richard Smith07b0fdc2013-03-18 21:12:30 +00008366void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8367 CXXConstructorDecl *Constructor) {
8368 CXXRecordDecl *ClassDecl = Constructor->getParent();
8369 assert(Constructor->getInheritedConstructor() &&
8370 !Constructor->doesThisDeclarationHaveABody() &&
8371 !Constructor->isDeleted());
8372
8373 SynthesizedFunctionScope Scope(*this, Constructor);
8374 DiagnosticErrorTrap Trap(Diags);
8375 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8376 Trap.hasErrorOccurred()) {
8377 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8378 << Context.getTagDeclType(ClassDecl);
8379 Constructor->setInvalidDecl();
8380 return;
8381 }
8382
8383 SourceLocation Loc = Constructor->getLocation();
8384 Constructor->setBody(new (Context) CompoundStmt(Loc));
8385
Eli Friedman86164e82013-09-05 00:02:25 +00008386 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008387 MarkVTableUsed(CurrentLocation, ClassDecl);
8388
8389 if (ASTMutationListener *L = getASTMutationListener()) {
8390 L->CompletedImplicitDefinition(Constructor);
8391 }
8392}
8393
8394
Sean Huntcb45a0f2011-05-12 22:46:25 +00008395Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008396Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8397 CXXRecordDecl *ClassDecl = MD->getParent();
8398
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008399 // C++ [except.spec]p14:
8400 // An implicitly declared special member function (Clause 12) shall have
8401 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008402 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008403 if (ClassDecl->isInvalidDecl())
8404 return ExceptSpec;
8405
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008406 // Direct base-class destructors.
8407 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8408 BEnd = ClassDecl->bases_end();
8409 B != BEnd; ++B) {
8410 if (B->isVirtual()) // Handled below.
8411 continue;
8412
8413 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008414 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008415 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008416 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008417
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008418 // Virtual base-class destructors.
8419 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8420 BEnd = ClassDecl->vbases_end();
8421 B != BEnd; ++B) {
8422 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008423 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008424 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008425 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008426
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008427 // Field destructors.
8428 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8429 FEnd = ClassDecl->field_end();
8430 F != FEnd; ++F) {
8431 if (const RecordType *RecordTy
8432 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008433 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008434 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008435 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008436
Sean Huntcb45a0f2011-05-12 22:46:25 +00008437 return ExceptSpec;
8438}
8439
8440CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8441 // C++ [class.dtor]p2:
8442 // If a class has no user-declared destructor, a destructor is
8443 // declared implicitly. An implicitly-declared destructor is an
8444 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008445 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008446
Richard Smithafb49182012-11-29 01:34:07 +00008447 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8448 if (DSM.isAlreadyBeingDeclared())
8449 return 0;
8450
Douglas Gregor4923aa22010-07-02 20:37:36 +00008451 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008452 CanQualType ClassType
8453 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008454 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008455 DeclarationName Name
8456 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008457 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008458 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008459 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8460 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008461 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008462 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008463 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008464 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008465
8466 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008467 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008468 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008469
Richard Smithbc2a35d2012-12-08 08:32:28 +00008470 AddOverriddenMethods(ClassDecl, Destructor);
8471
8472 // We don't need to use SpecialMemberIsTrivial here; triviality for
8473 // destructors is easy to compute.
8474 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8475
8476 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008477 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008478
Douglas Gregor4923aa22010-07-02 20:37:36 +00008479 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008480 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008481
Douglas Gregor4923aa22010-07-02 20:37:36 +00008482 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008483 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008484 PushOnScopeChains(Destructor, S, false);
8485 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008486
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008487 return Destructor;
8488}
8489
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008490void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008491 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008492 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008493 !Destructor->doesThisDeclarationHaveABody() &&
8494 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008495 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008496 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008497 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008498
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008499 if (Destructor->isInvalidDecl())
8500 return;
8501
Eli Friedman9a14db32012-10-18 20:14:08 +00008502 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008503
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008504 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008505 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8506 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008507
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008508 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008509 Diag(CurrentLocation, diag::note_member_synthesized_at)
8510 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8511
8512 Destructor->setInvalidDecl();
8513 return;
8514 }
8515
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008516 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008517 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008518 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008519 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008520
8521 if (ASTMutationListener *L = getASTMutationListener()) {
8522 L->CompletedImplicitDefinition(Destructor);
8523 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008524}
8525
Richard Smitha4156b82012-04-21 18:42:51 +00008526/// \brief Perform any semantic analysis which needs to be delayed until all
8527/// pending class member declarations have been parsed.
8528void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008529 // If the context is an invalid C++ class, just suppress these checks.
8530 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8531 if (Record->isInvalidDecl()) {
8532 DelayedDestructorExceptionSpecChecks.clear();
8533 return;
8534 }
8535 }
8536
Richard Smitha4156b82012-04-21 18:42:51 +00008537 // Perform any deferred checking of exception specifications for virtual
8538 // destructors.
8539 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8540 i != e; ++i) {
8541 const CXXDestructorDecl *Dtor =
8542 DelayedDestructorExceptionSpecChecks[i].first;
8543 assert(!Dtor->getParent()->isDependentType() &&
8544 "Should not ever add destructors of templates into the list.");
8545 CheckOverridingFunctionExceptionSpec(Dtor,
8546 DelayedDestructorExceptionSpecChecks[i].second);
8547 }
8548 DelayedDestructorExceptionSpecChecks.clear();
8549}
8550
Richard Smithb9d0b762012-07-27 04:22:15 +00008551void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8552 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008553 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008554 "adjusting dtor exception specs was introduced in c++11");
8555
Sebastian Redl0ee33912011-05-19 05:13:44 +00008556 // C++11 [class.dtor]p3:
8557 // A declaration of a destructor that does not have an exception-
8558 // specification is implicitly considered to have the same exception-
8559 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008560 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008561 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008562 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008563 return;
8564
Chandler Carruth3f224b22011-09-20 04:55:26 +00008565 // Replace the destructor's type, building off the existing one. Fortunately,
8566 // the only thing of interest in the destructor type is its extended info.
8567 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008568 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8569 EPI.ExceptionSpecType = EST_Unevaluated;
8570 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008571 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008572
Sebastian Redl0ee33912011-05-19 05:13:44 +00008573 // FIXME: If the destructor has a body that could throw, and the newly created
8574 // spec doesn't allow exceptions, we should emit a warning, because this
8575 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008576 // However, we don't have a body or an exception specification yet, so it
8577 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008578}
8579
Pavel Labath66ea35d2013-08-30 08:52:28 +00008580namespace {
8581/// \brief An abstract base class for all helper classes used in building the
8582// copy/move operators. These classes serve as factory functions and help us
8583// avoid using the same Expr* in the AST twice.
8584class ExprBuilder {
8585 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8586 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8587
8588protected:
8589 static Expr *assertNotNull(Expr *E) {
8590 assert(E && "Expression construction must not fail.");
8591 return E;
8592 }
8593
8594public:
8595 ExprBuilder() {}
8596 virtual ~ExprBuilder() {}
8597
8598 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8599};
8600
8601class RefBuilder: public ExprBuilder {
8602 VarDecl *Var;
8603 QualType VarType;
8604
8605public:
8606 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8607 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8608 }
8609
8610 RefBuilder(VarDecl *Var, QualType VarType)
8611 : Var(Var), VarType(VarType) {}
8612};
8613
8614class ThisBuilder: public ExprBuilder {
8615public:
8616 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8617 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8618 }
8619};
8620
8621class CastBuilder: public ExprBuilder {
8622 const ExprBuilder &Builder;
8623 QualType Type;
8624 ExprValueKind Kind;
8625 const CXXCastPath &Path;
8626
8627public:
8628 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8629 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8630 CK_UncheckedDerivedToBase, Kind,
8631 &Path).take());
8632 }
8633
8634 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8635 const CXXCastPath &Path)
8636 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8637};
8638
8639class DerefBuilder: public ExprBuilder {
8640 const ExprBuilder &Builder;
8641
8642public:
8643 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8644 return assertNotNull(
8645 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8646 }
8647
8648 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8649};
8650
8651class MemberBuilder: public ExprBuilder {
8652 const ExprBuilder &Builder;
8653 QualType Type;
8654 CXXScopeSpec SS;
8655 bool IsArrow;
8656 LookupResult &MemberLookup;
8657
8658public:
8659 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8660 return assertNotNull(S.BuildMemberReferenceExpr(
8661 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8662 MemberLookup, 0).take());
8663 }
8664
8665 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8666 LookupResult &MemberLookup)
8667 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8668 MemberLookup(MemberLookup) {}
8669};
8670
8671class MoveCastBuilder: public ExprBuilder {
8672 const ExprBuilder &Builder;
8673
8674public:
8675 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8676 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8677 }
8678
8679 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8680};
8681
8682class LvalueConvBuilder: public ExprBuilder {
8683 const ExprBuilder &Builder;
8684
8685public:
8686 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8687 return assertNotNull(
8688 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8689 }
8690
8691 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8692};
8693
8694class SubscriptBuilder: public ExprBuilder {
8695 const ExprBuilder &Base;
8696 const ExprBuilder &Index;
8697
8698public:
8699 virtual Expr *build(Sema &S, SourceLocation Loc) const
8700 LLVM_OVERRIDE {
8701 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8702 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8703 }
8704
8705 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8706 : Base(Base), Index(Index) {}
8707};
8708
8709} // end anonymous namespace
8710
Richard Smith8c889532012-11-14 00:50:40 +00008711/// When generating a defaulted copy or move assignment operator, if a field
8712/// should be copied with __builtin_memcpy rather than via explicit assignments,
8713/// do so. This optimization only applies for arrays of scalars, and for arrays
8714/// of class type where the selected copy/move-assignment operator is trivial.
8715static StmtResult
8716buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008717 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008718 // Compute the size of the memory buffer to be copied.
8719 QualType SizeType = S.Context.getSizeType();
8720 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8721 S.Context.getTypeSizeInChars(T).getQuantity());
8722
8723 // Take the address of the field references for "from" and "to". We
8724 // directly construct UnaryOperators here because semantic analysis
8725 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008726 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008727 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8728 S.Context.getPointerType(From->getType()),
8729 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008730 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008731 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8732 S.Context.getPointerType(To->getType()),
8733 VK_RValue, OK_Ordinary, Loc);
8734
8735 const Type *E = T->getBaseElementTypeUnsafe();
8736 bool NeedsCollectableMemCpy =
8737 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8738
8739 // Create a reference to the __builtin_objc_memmove_collectable function
8740 StringRef MemCpyName = NeedsCollectableMemCpy ?
8741 "__builtin_objc_memmove_collectable" :
8742 "__builtin_memcpy";
8743 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8744 Sema::LookupOrdinaryName);
8745 S.LookupName(R, S.TUScope, true);
8746
8747 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8748 if (!MemCpy)
8749 // Something went horribly wrong earlier, and we will have complained
8750 // about it.
8751 return StmtError();
8752
8753 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8754 VK_RValue, Loc, 0);
8755 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8756
8757 Expr *CallArgs[] = {
8758 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8759 };
8760 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8761 Loc, CallArgs, Loc);
8762
8763 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8764 return S.Owned(Call.takeAs<Stmt>());
8765}
8766
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008767/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008768/// \c To.
8769///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008770/// This routine is used to copy/move the members of a class with an
8771/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008772/// copied are arrays, this routine builds for loops to copy them.
8773///
8774/// \param S The Sema object used for type-checking.
8775///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008777///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008778/// \param T The type of the expressions being copied/moved. Both expressions
8779/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008780///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008781/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008782///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008783/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008784///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008785/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008786/// Otherwise, it's a non-static member subobject.
8787///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008788/// \param Copying Whether we're copying or moving.
8789///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008790/// \param Depth Internal parameter recording the depth of the recursion.
8791///
Richard Smith8c889532012-11-14 00:50:40 +00008792/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8793/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008794static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008795buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008796 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008797 bool CopyingBaseSubobject, bool Copying,
8798 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008799 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008800 // Each subobject is assigned in the manner appropriate to its type:
8801 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008802 // - if the subobject is of class type, as if by a call to operator= with
8803 // the subobject as the object expression and the corresponding
8804 // subobject of x as a single function argument (as if by explicit
8805 // qualification; that is, ignoring any possible virtual overriding
8806 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008807 //
8808 // C++03 [class.copy]p13:
8809 // - if the subobject is of class type, the copy assignment operator for
8810 // the class is used (as if by explicit qualification; that is,
8811 // ignoring any possible virtual overriding functions in more derived
8812 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008813 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8814 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008815
Douglas Gregor06a9f362010-05-01 20:49:11 +00008816 // Look for operator=.
8817 DeclarationName Name
8818 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8819 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8820 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008821
Richard Smith044c8aa2012-11-13 00:54:12 +00008822 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8823 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008824 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008825 LookupResult::Filter F = OpLookup.makeFilter();
8826 while (F.hasNext()) {
8827 NamedDecl *D = F.next();
8828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8829 if (Method->isCopyAssignmentOperator() ||
8830 (!Copying && Method->isMoveAssignmentOperator()))
8831 continue;
8832
8833 F.erase();
8834 }
8835 F.done();
John McCallb0207482010-03-16 06:11:48 +00008836 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008837
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008838 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008839 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008840 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008841 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008842 // ambiguities), we need to cast "this" to that subobject type; to
8843 // ensure that we don't go through the virtual call mechanism, we need
8844 // to qualify the operator= name with the base class (see below). However,
8845 // this means that if the base class has a protected copy assignment
8846 // operator, the protected member access check will fail. So, we
8847 // rewrite "protected" access to "public" access in this case, since we
8848 // know by construction that we're calling from a derived class.
8849 if (CopyingBaseSubobject) {
8850 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8851 L != LEnd; ++L) {
8852 if (L.getAccess() == AS_protected)
8853 L.setAccess(AS_public);
8854 }
8855 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008856
Douglas Gregor06a9f362010-05-01 20:49:11 +00008857 // Create the nested-name-specifier that will be used to qualify the
8858 // reference to operator=; this is required to suppress the virtual
8859 // call mechanism.
8860 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008861 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008862 SS.MakeTrivial(S.Context,
8863 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008864 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008865 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008866
Douglas Gregor06a9f362010-05-01 20:49:11 +00008867 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008868 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00008869 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8870 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008871 /*FirstQualifierInScope=*/0,
8872 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008873 /*TemplateArgs=*/0,
8874 /*SuppressQualifierCheck=*/true);
8875 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008876 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008877
Douglas Gregor06a9f362010-05-01 20:49:11 +00008878 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008879
Pavel Labath66ea35d2013-08-30 08:52:28 +00008880 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008881 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008882 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008883 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008884 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008885 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008886
Richard Smith8c889532012-11-14 00:50:40 +00008887 // If we built a call to a trivial 'operator=' while copying an array,
8888 // bail out. We'll replace the whole shebang with a memcpy.
8889 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8890 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8891 return StmtResult((Stmt*)0);
8892
Richard Smith044c8aa2012-11-13 00:54:12 +00008893 // Convert to an expression-statement, and clean up any produced
8894 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008895 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008896 }
John McCallb0207482010-03-16 06:11:48 +00008897
Richard Smith044c8aa2012-11-13 00:54:12 +00008898 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008899 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008900 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008901 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00008902 ExprResult Assignment = S.CreateBuiltinBinOp(
8903 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008904 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008905 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008906 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008907 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008908
8909 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008910 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008911
Douglas Gregor06a9f362010-05-01 20:49:11 +00008912 // Construct a loop over the array bounds, e.g.,
8913 //
8914 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8915 //
8916 // that will copy each of the array elements.
8917 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008918
Douglas Gregor06a9f362010-05-01 20:49:11 +00008919 // Create the iteration variable.
8920 IdentifierInfo *IterationVarName = 0;
8921 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008922 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008923 llvm::raw_svector_ostream OS(Str);
8924 OS << "__i" << Depth;
8925 IterationVarName = &S.Context.Idents.get(OS.str());
8926 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008927 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008928 IterationVarName, SizeType,
8929 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008930 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008931
Douglas Gregor06a9f362010-05-01 20:49:11 +00008932 // Initialize the iteration variable to zero.
8933 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008934 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008935
Pavel Labath66ea35d2013-08-30 08:52:28 +00008936 // Creates a reference to the iteration variable.
8937 RefBuilder IterationVarRef(IterationVar, SizeType);
8938 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00008939
Douglas Gregor06a9f362010-05-01 20:49:11 +00008940 // Create the DeclStmt that holds the iteration variable.
8941 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008942
Douglas Gregor06a9f362010-05-01 20:49:11 +00008943 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008944 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
8945 MoveCastBuilder FromIndexMove(FromIndexCopy);
8946 const ExprBuilder *FromIndex;
8947 if (Copying)
8948 FromIndex = &FromIndexCopy;
8949 else
8950 FromIndex = &FromIndexMove;
8951
8952 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008953
8954 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008955 StmtResult Copy =
8956 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008957 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00008958 Copying, Depth + 1);
8959 // Bail out if copying fails or if we determined that we should use memcpy.
8960 if (Copy.isInvalid() || !Copy.get())
8961 return Copy;
8962
8963 // Create the comparison against the array bound.
8964 llvm::APInt Upper
8965 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8966 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00008967 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00008968 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8969 BO_NE, S.Context.BoolTy,
8970 VK_RValue, OK_Ordinary, Loc, false);
8971
8972 // Create the pre-increment of the iteration variable.
8973 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00008974 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
8975 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008976
Douglas Gregor06a9f362010-05-01 20:49:11 +00008977 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008978 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008979 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008980 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008981 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008982}
8983
Richard Smith8c889532012-11-14 00:50:40 +00008984static StmtResult
8985buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008986 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008987 bool CopyingBaseSubobject, bool Copying) {
8988 // Maybe we should use a memcpy?
8989 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8990 T.isTriviallyCopyableType(S.Context))
8991 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8992
8993 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8994 CopyingBaseSubobject,
8995 Copying, 0));
8996
8997 // If we ended up picking a trivial assignment operator for an array of a
8998 // non-trivially-copyable class type, just emit a memcpy.
8999 if (!Result.isInvalid() && !Result.get())
9000 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9001
9002 return Result;
9003}
9004
Richard Smithb9d0b762012-07-27 04:22:15 +00009005Sema::ImplicitExceptionSpecification
9006Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9007 CXXRecordDecl *ClassDecl = MD->getParent();
9008
9009 ImplicitExceptionSpecification ExceptSpec(*this);
9010 if (ClassDecl->isInvalidDecl())
9011 return ExceptSpec;
9012
9013 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9014 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9015 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9016
Douglas Gregorb87786f2010-07-01 17:48:08 +00009017 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009018 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009019 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009020
9021 // It is unspecified whether or not an implicit copy assignment operator
9022 // attempts to deduplicate calls to assignment operators of virtual bases are
9023 // made. As such, this exception specification is effectively unspecified.
9024 // Based on a similar decision made for constness in C++0x, we're erring on
9025 // the side of assuming such calls to be made regardless of whether they
9026 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00009027 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9028 BaseEnd = ClassDecl->bases_end();
9029 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009030 if (Base->isVirtual())
9031 continue;
9032
Douglas Gregora376d102010-07-02 21:50:04 +00009033 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00009034 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009035 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9036 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009037 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009038 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009039
9040 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9041 BaseEnd = ClassDecl->vbases_end();
9042 Base != BaseEnd; ++Base) {
9043 CXXRecordDecl *BaseClassDecl
9044 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9045 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9046 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009047 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009048 }
9049
Douglas Gregorb87786f2010-07-01 17:48:08 +00009050 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9051 FieldEnd = ClassDecl->field_end();
9052 Field != FieldEnd;
9053 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009054 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009055 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9056 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009057 LookupCopyingAssignment(FieldClassDecl,
9058 ArgQuals | FieldType.getCVRQualifiers(),
9059 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009060 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009061 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009062 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009063
Richard Smithb9d0b762012-07-27 04:22:15 +00009064 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009065}
9066
9067CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9068 // Note: The following rules are largely analoguous to the copy
9069 // constructor rules. Note that virtual bases are not taken into account
9070 // for determining the argument type of the operator. Note also that
9071 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009072 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009073
Richard Smithafb49182012-11-29 01:34:07 +00009074 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9075 if (DSM.isAlreadyBeingDeclared())
9076 return 0;
9077
Sean Hunt30de05c2011-05-14 05:23:20 +00009078 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9079 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009080 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9081 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009082 ArgType = ArgType.withConst();
9083 ArgType = Context.getLValueReferenceType(ArgType);
9084
Richard Smitha8942d72013-05-07 03:19:20 +00009085 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9086 CXXCopyAssignment,
9087 Const);
9088
Douglas Gregord3c35902010-07-01 16:36:15 +00009089 // An implicitly-declared copy assignment operator is an inline public
9090 // member of its class.
9091 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009092 SourceLocation ClassLoc = ClassDecl->getLocation();
9093 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009094 CXXMethodDecl *CopyAssignment =
9095 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9096 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9097 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009098 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009099 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009100 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009101
9102 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009103 FunctionProtoType::ExtProtoInfo EPI =
9104 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009105 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009106
Douglas Gregord3c35902010-07-01 16:36:15 +00009107 // Add the parameter to the operator.
9108 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009109 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009110 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009111 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009112 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009113
Richard Smithbc2a35d2012-12-08 08:32:28 +00009114 AddOverriddenMethods(ClassDecl, CopyAssignment);
9115
9116 CopyAssignment->setTrivial(
9117 ClassDecl->needsOverloadResolutionForCopyAssignment()
9118 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9119 : ClassDecl->hasTrivialCopyAssignment());
9120
Richard Smitha8942d72013-05-07 03:19:20 +00009121 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009122 // .... If the class definition does not explicitly declare a copy
9123 // assignment operator, there is no user-declared move constructor, and
9124 // there is no user-declared move assignment operator, a copy assignment
9125 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009126 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009127 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009128
Richard Smithbc2a35d2012-12-08 08:32:28 +00009129 // Note that we have added this copy-assignment operator.
9130 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9131
9132 if (Scope *S = getScopeForContext(ClassDecl))
9133 PushOnScopeChains(CopyAssignment, S, false);
9134 ClassDecl->addDecl(CopyAssignment);
9135
Douglas Gregord3c35902010-07-01 16:36:15 +00009136 return CopyAssignment;
9137}
9138
Richard Smith36155c12013-06-13 03:23:42 +00009139/// Diagnose an implicit copy operation for a class which is odr-used, but
9140/// which is deprecated because the class has a user-declared copy constructor,
9141/// copy assignment operator, or destructor.
9142static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9143 SourceLocation UseLoc) {
9144 assert(CopyOp->isImplicit());
9145
9146 CXXRecordDecl *RD = CopyOp->getParent();
9147 CXXMethodDecl *UserDeclaredOperation = 0;
9148
9149 // In Microsoft mode, assignment operations don't affect constructors and
9150 // vice versa.
9151 if (RD->hasUserDeclaredDestructor()) {
9152 UserDeclaredOperation = RD->getDestructor();
9153 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9154 RD->hasUserDeclaredCopyConstructor() &&
9155 !S.getLangOpts().MicrosoftMode) {
9156 // Find any user-declared copy constructor.
9157 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9158 E = RD->ctor_end(); I != E; ++I) {
9159 if (I->isCopyConstructor()) {
9160 UserDeclaredOperation = *I;
9161 break;
9162 }
9163 }
9164 assert(UserDeclaredOperation);
9165 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9166 RD->hasUserDeclaredCopyAssignment() &&
9167 !S.getLangOpts().MicrosoftMode) {
9168 // Find any user-declared move assignment operator.
9169 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9170 E = RD->method_end(); I != E; ++I) {
9171 if (I->isCopyAssignmentOperator()) {
9172 UserDeclaredOperation = *I;
9173 break;
9174 }
9175 }
9176 assert(UserDeclaredOperation);
9177 }
9178
9179 if (UserDeclaredOperation) {
9180 S.Diag(UserDeclaredOperation->getLocation(),
9181 diag::warn_deprecated_copy_operation)
9182 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9183 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9184 S.Diag(UseLoc, diag::note_member_synthesized_at)
9185 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9186 : Sema::CXXCopyAssignment)
9187 << RD;
9188 }
9189}
9190
Douglas Gregor06a9f362010-05-01 20:49:11 +00009191void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9192 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009193 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009194 CopyAssignOperator->isOverloadedOperator() &&
9195 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009196 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9197 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009198 "DefineImplicitCopyAssignment called for wrong function");
9199
9200 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9201
9202 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9203 CopyAssignOperator->setInvalidDecl();
9204 return;
9205 }
Richard Smith36155c12013-06-13 03:23:42 +00009206
9207 // C++11 [class.copy]p18:
9208 // The [definition of an implicitly declared copy assignment operator] is
9209 // deprecated if the class has a user-declared copy constructor or a
9210 // user-declared destructor.
9211 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9212 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9213
Eli Friedman86164e82013-09-05 00:02:25 +00009214 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009215
Eli Friedman9a14db32012-10-18 20:14:08 +00009216 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009217 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009218
9219 // C++0x [class.copy]p30:
9220 // The implicitly-defined or explicitly-defaulted copy assignment operator
9221 // for a non-union class X performs memberwise copy assignment of its
9222 // subobjects. The direct base classes of X are assigned first, in the
9223 // order of their declaration in the base-specifier-list, and then the
9224 // immediate non-static data members of X are assigned, in the order in
9225 // which they were declared in the class definition.
9226
9227 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009228 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009229
9230 // The parameter for the "other" object, which we are copying from.
9231 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9232 Qualifiers OtherQuals = Other->getType().getQualifiers();
9233 QualType OtherRefType = Other->getType();
9234 if (const LValueReferenceType *OtherRef
9235 = OtherRefType->getAs<LValueReferenceType>()) {
9236 OtherRefType = OtherRef->getPointeeType();
9237 OtherQuals = OtherRefType.getQualifiers();
9238 }
9239
9240 // Our location for everything implicitly-generated.
9241 SourceLocation Loc = CopyAssignOperator->getLocation();
9242
Pavel Labath66ea35d2013-08-30 08:52:28 +00009243 // Builds a DeclRefExpr for the "other" object.
9244 RefBuilder OtherRef(Other, OtherRefType);
9245
9246 // Builds the "this" pointer.
9247 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009248
9249 // Assign base classes.
9250 bool Invalid = false;
9251 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9252 E = ClassDecl->bases_end(); Base != E; ++Base) {
9253 // Form the assignment:
9254 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9255 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009256 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009257 Invalid = true;
9258 continue;
9259 }
9260
John McCallf871d0c2010-08-07 06:22:56 +00009261 CXXCastPath BasePath;
9262 BasePath.push_back(Base);
9263
Douglas Gregor06a9f362010-05-01 20:49:11 +00009264 // Construct the "from" expression, which is an implicit cast to the
9265 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009266 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9267 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009268
9269 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009270 DerefBuilder DerefThis(This);
9271 CastBuilder To(DerefThis,
9272 Context.getCVRQualifiedType(
9273 BaseType, CopyAssignOperator->getTypeQualifiers()),
9274 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009275
9276 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009277 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009278 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009279 /*CopyingBaseSubobject=*/true,
9280 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009281 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009282 Diag(CurrentLocation, diag::note_member_synthesized_at)
9283 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9284 CopyAssignOperator->setInvalidDecl();
9285 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009286 }
9287
9288 // Success! Record the copy.
9289 Statements.push_back(Copy.takeAs<Expr>());
9290 }
9291
Douglas Gregor06a9f362010-05-01 20:49:11 +00009292 // Assign non-static members.
9293 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9294 FieldEnd = ClassDecl->field_end();
9295 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009296 if (Field->isUnnamedBitfield())
9297 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009298
9299 if (Field->isInvalidDecl()) {
9300 Invalid = true;
9301 continue;
9302 }
9303
Douglas Gregor06a9f362010-05-01 20:49:11 +00009304 // Check for members of reference type; we can't copy those.
9305 if (Field->getType()->isReferenceType()) {
9306 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9307 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9308 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009309 Diag(CurrentLocation, diag::note_member_synthesized_at)
9310 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009311 Invalid = true;
9312 continue;
9313 }
9314
9315 // Check for members of const-qualified, non-class type.
9316 QualType BaseType = Context.getBaseElementType(Field->getType());
9317 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9318 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9319 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9320 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009321 Diag(CurrentLocation, diag::note_member_synthesized_at)
9322 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009323 Invalid = true;
9324 continue;
9325 }
John McCallb77115d2011-06-17 00:18:42 +00009326
9327 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009328 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9329 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009330
9331 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009332 if (FieldType->isIncompleteArrayType()) {
9333 assert(ClassDecl->hasFlexibleArrayMember() &&
9334 "Incomplete array type is not valid");
9335 continue;
9336 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009337
9338 // Build references to the field in the object we're copying from and to.
9339 CXXScopeSpec SS; // Intentionally empty
9340 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9341 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009342 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009343 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009344
9345 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9346
9347 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009348
Douglas Gregor06a9f362010-05-01 20:49:11 +00009349 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009350 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009351 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009352 /*CopyingBaseSubobject=*/false,
9353 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009354 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009355 Diag(CurrentLocation, diag::note_member_synthesized_at)
9356 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9357 CopyAssignOperator->setInvalidDecl();
9358 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009359 }
9360
9361 // Success! Record the copy.
9362 Statements.push_back(Copy.takeAs<Stmt>());
9363 }
9364
9365 if (!Invalid) {
9366 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009367 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009368
John McCall60d7b3a2010-08-24 06:29:42 +00009369 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009370 if (Return.isInvalid())
9371 Invalid = true;
9372 else {
9373 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009374
9375 if (Trap.hasErrorOccurred()) {
9376 Diag(CurrentLocation, diag::note_member_synthesized_at)
9377 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9378 Invalid = true;
9379 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009380 }
9381 }
9382
9383 if (Invalid) {
9384 CopyAssignOperator->setInvalidDecl();
9385 return;
9386 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009387
9388 StmtResult Body;
9389 {
9390 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009391 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009392 /*isStmtExpr=*/false);
9393 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9394 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009395 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009396
9397 if (ASTMutationListener *L = getASTMutationListener()) {
9398 L->CompletedImplicitDefinition(CopyAssignOperator);
9399 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009400}
9401
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009402Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009403Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9404 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009405
Richard Smithb9d0b762012-07-27 04:22:15 +00009406 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009407 if (ClassDecl->isInvalidDecl())
9408 return ExceptSpec;
9409
9410 // C++0x [except.spec]p14:
9411 // An implicitly declared special member function (Clause 12) shall have an
9412 // exception-specification. [...]
9413
9414 // It is unspecified whether or not an implicit move assignment operator
9415 // attempts to deduplicate calls to assignment operators of virtual bases are
9416 // made. As such, this exception specification is effectively unspecified.
9417 // Based on a similar decision made for constness in C++0x, we're erring on
9418 // the side of assuming such calls to be made regardless of whether they
9419 // actually happen.
9420 // Note that a move constructor is not implicitly declared when there are
9421 // virtual bases, but it can still be user-declared and explicitly defaulted.
9422 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9423 BaseEnd = ClassDecl->bases_end();
9424 Base != BaseEnd; ++Base) {
9425 if (Base->isVirtual())
9426 continue;
9427
9428 CXXRecordDecl *BaseClassDecl
9429 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9430 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009431 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009432 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009433 }
9434
9435 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9436 BaseEnd = ClassDecl->vbases_end();
9437 Base != BaseEnd; ++Base) {
9438 CXXRecordDecl *BaseClassDecl
9439 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9440 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009441 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009442 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009443 }
9444
9445 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9446 FieldEnd = ClassDecl->field_end();
9447 Field != FieldEnd;
9448 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009449 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009450 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009451 if (CXXMethodDecl *MoveAssign =
9452 LookupMovingAssignment(FieldClassDecl,
9453 FieldType.getCVRQualifiers(),
9454 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009455 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009456 }
9457 }
9458
9459 return ExceptSpec;
9460}
9461
Richard Smith1c931be2012-04-02 18:40:40 +00009462/// Determine whether the class type has any direct or indirect virtual base
9463/// classes which have a non-trivial move assignment operator.
9464static bool
9465hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9466 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9467 BaseEnd = ClassDecl->vbases_end();
9468 Base != BaseEnd; ++Base) {
9469 CXXRecordDecl *BaseClass =
9470 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9471
9472 // Try to declare the move assignment. If it would be deleted, then the
9473 // class does not have a non-trivial move assignment.
9474 if (BaseClass->needsImplicitMoveAssignment())
9475 S.DeclareImplicitMoveAssignment(BaseClass);
9476
Richard Smith426391c2012-11-16 00:53:38 +00009477 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009478 return true;
9479 }
9480
9481 return false;
9482}
9483
9484/// Determine whether the given type either has a move constructor or is
9485/// trivially copyable.
9486static bool
9487hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9488 Type = S.Context.getBaseElementType(Type);
9489
9490 // FIXME: Technically, non-trivially-copyable non-class types, such as
9491 // reference types, are supposed to return false here, but that appears
9492 // to be a standard defect.
9493 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009494 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009495 return true;
9496
9497 if (Type.isTriviallyCopyableType(S.Context))
9498 return true;
9499
9500 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009501 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9502 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009503 if (ClassDecl->needsImplicitMoveConstructor())
9504 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009505 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009506 }
9507
Richard Smithe5411b72012-12-01 02:35:44 +00009508 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9509 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009510 if (ClassDecl->needsImplicitMoveAssignment())
9511 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009512 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009513}
9514
9515/// Determine whether all non-static data members and direct or virtual bases
9516/// of class \p ClassDecl have either a move operation, or are trivially
9517/// copyable.
9518static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9519 bool IsConstructor) {
9520 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9521 BaseEnd = ClassDecl->bases_end();
9522 Base != BaseEnd; ++Base) {
9523 if (Base->isVirtual())
9524 continue;
9525
9526 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9527 return false;
9528 }
9529
9530 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9531 BaseEnd = ClassDecl->vbases_end();
9532 Base != BaseEnd; ++Base) {
9533 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9534 return false;
9535 }
9536
9537 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9538 FieldEnd = ClassDecl->field_end();
9539 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009540 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009541 return false;
9542 }
9543
9544 return true;
9545}
9546
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009547CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009548 // C++11 [class.copy]p20:
9549 // If the definition of a class X does not explicitly declare a move
9550 // assignment operator, one will be implicitly declared as defaulted
9551 // if and only if:
9552 //
9553 // - [first 4 bullets]
9554 assert(ClassDecl->needsImplicitMoveAssignment());
9555
Richard Smithafb49182012-11-29 01:34:07 +00009556 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9557 if (DSM.isAlreadyBeingDeclared())
9558 return 0;
9559
Richard Smith1c931be2012-04-02 18:40:40 +00009560 // [Checked after we build the declaration]
9561 // - the move assignment operator would not be implicitly defined as
9562 // deleted,
9563
9564 // [DR1402]:
9565 // - X has no direct or indirect virtual base class with a non-trivial
9566 // move assignment operator, and
9567 // - each of X's non-static data members and direct or virtual base classes
9568 // has a type that either has a move assignment operator or is trivially
9569 // copyable.
9570 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9571 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9572 ClassDecl->setFailedImplicitMoveAssignment();
9573 return 0;
9574 }
9575
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009576 // Note: The following rules are largely analoguous to the move
9577 // constructor rules.
9578
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009579 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9580 QualType RetType = Context.getLValueReferenceType(ArgType);
9581 ArgType = Context.getRValueReferenceType(ArgType);
9582
Richard Smitha8942d72013-05-07 03:19:20 +00009583 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9584 CXXMoveAssignment,
9585 false);
9586
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009587 // An implicitly-declared move assignment operator is an inline public
9588 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009589 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9590 SourceLocation ClassLoc = ClassDecl->getLocation();
9591 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009592 CXXMethodDecl *MoveAssignment =
9593 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9594 /*TInfo=*/0, /*StorageClass=*/SC_None,
9595 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009596 MoveAssignment->setAccess(AS_public);
9597 MoveAssignment->setDefaulted();
9598 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009599
Richard Smithb9d0b762012-07-27 04:22:15 +00009600 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009601 FunctionProtoType::ExtProtoInfo EPI =
9602 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009603 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009604
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009605 // Add the parameter to the operator.
9606 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9607 ClassLoc, ClassLoc, /*Id=*/0,
9608 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009609 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009610 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009611
Richard Smithbc2a35d2012-12-08 08:32:28 +00009612 AddOverriddenMethods(ClassDecl, MoveAssignment);
9613
9614 MoveAssignment->setTrivial(
9615 ClassDecl->needsOverloadResolutionForMoveAssignment()
9616 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9617 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009618
9619 // C++0x [class.copy]p9:
9620 // If the definition of a class X does not explicitly declare a move
9621 // assignment operator, one will be implicitly declared as defaulted if and
9622 // only if:
9623 // [...]
9624 // - the move assignment operator would not be implicitly defined as
9625 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009626 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009627 // Cache this result so that we don't try to generate this over and over
9628 // on every lookup, leaking memory and wasting time.
9629 ClassDecl->setFailedImplicitMoveAssignment();
9630 return 0;
9631 }
9632
Richard Smithbc2a35d2012-12-08 08:32:28 +00009633 // Note that we have added this copy-assignment operator.
9634 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9635
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009636 if (Scope *S = getScopeForContext(ClassDecl))
9637 PushOnScopeChains(MoveAssignment, S, false);
9638 ClassDecl->addDecl(MoveAssignment);
9639
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009640 return MoveAssignment;
9641}
9642
9643void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9644 CXXMethodDecl *MoveAssignOperator) {
9645 assert((MoveAssignOperator->isDefaulted() &&
9646 MoveAssignOperator->isOverloadedOperator() &&
9647 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009648 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9649 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009650 "DefineImplicitMoveAssignment called for wrong function");
9651
9652 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9653
9654 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9655 MoveAssignOperator->setInvalidDecl();
9656 return;
9657 }
9658
Eli Friedman86164e82013-09-05 00:02:25 +00009659 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009660
Eli Friedman9a14db32012-10-18 20:14:08 +00009661 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009662 DiagnosticErrorTrap Trap(Diags);
9663
9664 // C++0x [class.copy]p28:
9665 // The implicitly-defined or move assignment operator for a non-union class
9666 // X performs memberwise move assignment of its subobjects. The direct base
9667 // classes of X are assigned first, in the order of their declaration in the
9668 // base-specifier-list, and then the immediate non-static data members of X
9669 // are assigned, in the order in which they were declared in the class
9670 // definition.
9671
9672 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009673 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009674
9675 // The parameter for the "other" object, which we are move from.
9676 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9677 QualType OtherRefType = Other->getType()->
9678 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009679 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009680 "Bad argument type of defaulted move assignment");
9681
9682 // Our location for everything implicitly-generated.
9683 SourceLocation Loc = MoveAssignOperator->getLocation();
9684
Pavel Labath66ea35d2013-08-30 08:52:28 +00009685 // Builds a reference to the "other" object.
9686 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009687 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009688 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009689
Pavel Labath66ea35d2013-08-30 08:52:28 +00009690 // Builds the "this" pointer.
9691 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009692
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009693 // Assign base classes.
9694 bool Invalid = false;
9695 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9696 E = ClassDecl->bases_end(); Base != E; ++Base) {
9697 // Form the assignment:
9698 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9699 QualType BaseType = Base->getType().getUnqualifiedType();
9700 if (!BaseType->isRecordType()) {
9701 Invalid = true;
9702 continue;
9703 }
9704
9705 CXXCastPath BasePath;
9706 BasePath.push_back(Base);
9707
9708 // Construct the "from" expression, which is an implicit cast to the
9709 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009710 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009711
9712 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009713 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009714
9715 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009716 CastBuilder To(DerefThis,
9717 Context.getCVRQualifiedType(
9718 BaseType, MoveAssignOperator->getTypeQualifiers()),
9719 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009720
9721 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009722 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009723 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009724 /*CopyingBaseSubobject=*/true,
9725 /*Copying=*/false);
9726 if (Move.isInvalid()) {
9727 Diag(CurrentLocation, diag::note_member_synthesized_at)
9728 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9729 MoveAssignOperator->setInvalidDecl();
9730 return;
9731 }
9732
9733 // Success! Record the move.
9734 Statements.push_back(Move.takeAs<Expr>());
9735 }
9736
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009737 // Assign non-static members.
9738 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9739 FieldEnd = ClassDecl->field_end();
9740 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009741 if (Field->isUnnamedBitfield())
9742 continue;
9743
Eli Friedman8150da32013-06-07 01:48:56 +00009744 if (Field->isInvalidDecl()) {
9745 Invalid = true;
9746 continue;
9747 }
9748
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009749 // Check for members of reference type; we can't move those.
9750 if (Field->getType()->isReferenceType()) {
9751 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9752 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9753 Diag(Field->getLocation(), diag::note_declared_at);
9754 Diag(CurrentLocation, diag::note_member_synthesized_at)
9755 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9756 Invalid = true;
9757 continue;
9758 }
9759
9760 // Check for members of const-qualified, non-class type.
9761 QualType BaseType = Context.getBaseElementType(Field->getType());
9762 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9763 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9764 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9765 Diag(Field->getLocation(), diag::note_declared_at);
9766 Diag(CurrentLocation, diag::note_member_synthesized_at)
9767 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9768 Invalid = true;
9769 continue;
9770 }
9771
9772 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009773 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9774 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009775
9776 QualType FieldType = Field->getType().getNonReferenceType();
9777 if (FieldType->isIncompleteArrayType()) {
9778 assert(ClassDecl->hasFlexibleArrayMember() &&
9779 "Incomplete array type is not valid");
9780 continue;
9781 }
9782
9783 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009784 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9785 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009786 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009787 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009788 MemberBuilder From(MoveOther, OtherRefType,
9789 /*IsArrow=*/false, MemberLookup);
9790 MemberBuilder To(This, getCurrentThisType(),
9791 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009792
Pavel Labath66ea35d2013-08-30 08:52:28 +00009793 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009794 "Member reference with rvalue base must be rvalue except for reference "
9795 "members, which aren't allowed for move assignment.");
9796
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009797 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009798 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009799 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009800 /*CopyingBaseSubobject=*/false,
9801 /*Copying=*/false);
9802 if (Move.isInvalid()) {
9803 Diag(CurrentLocation, diag::note_member_synthesized_at)
9804 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9805 MoveAssignOperator->setInvalidDecl();
9806 return;
9807 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009808
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009809 // Success! Record the copy.
9810 Statements.push_back(Move.takeAs<Stmt>());
9811 }
9812
9813 if (!Invalid) {
9814 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009815 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009816
9817 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9818 if (Return.isInvalid())
9819 Invalid = true;
9820 else {
9821 Statements.push_back(Return.takeAs<Stmt>());
9822
9823 if (Trap.hasErrorOccurred()) {
9824 Diag(CurrentLocation, diag::note_member_synthesized_at)
9825 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9826 Invalid = true;
9827 }
9828 }
9829 }
9830
9831 if (Invalid) {
9832 MoveAssignOperator->setInvalidDecl();
9833 return;
9834 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009835
9836 StmtResult Body;
9837 {
9838 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009839 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009840 /*isStmtExpr=*/false);
9841 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9842 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009843 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9844
9845 if (ASTMutationListener *L = getASTMutationListener()) {
9846 L->CompletedImplicitDefinition(MoveAssignOperator);
9847 }
9848}
9849
Richard Smithb9d0b762012-07-27 04:22:15 +00009850Sema::ImplicitExceptionSpecification
9851Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9852 CXXRecordDecl *ClassDecl = MD->getParent();
9853
9854 ImplicitExceptionSpecification ExceptSpec(*this);
9855 if (ClassDecl->isInvalidDecl())
9856 return ExceptSpec;
9857
9858 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9859 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9860 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9861
Douglas Gregor0d405db2010-07-01 20:59:04 +00009862 // C++ [except.spec]p14:
9863 // An implicitly declared special member function (Clause 12) shall have an
9864 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009865 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9866 BaseEnd = ClassDecl->bases_end();
9867 Base != BaseEnd;
9868 ++Base) {
9869 // Virtual bases are handled below.
9870 if (Base->isVirtual())
9871 continue;
9872
Douglas Gregor22584312010-07-02 23:41:54 +00009873 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009874 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009875 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009876 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009877 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009878 }
9879 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9880 BaseEnd = ClassDecl->vbases_end();
9881 Base != BaseEnd;
9882 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009883 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009884 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009885 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009886 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009887 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009888 }
9889 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9890 FieldEnd = ClassDecl->field_end();
9891 Field != FieldEnd;
9892 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009893 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009894 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9895 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009896 LookupCopyingConstructor(FieldClassDecl,
9897 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009898 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009899 }
9900 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009901
Richard Smithb9d0b762012-07-27 04:22:15 +00009902 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009903}
9904
9905CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9906 CXXRecordDecl *ClassDecl) {
9907 // C++ [class.copy]p4:
9908 // If the class definition does not explicitly declare a copy
9909 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009910 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009911
Richard Smithafb49182012-11-29 01:34:07 +00009912 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9913 if (DSM.isAlreadyBeingDeclared())
9914 return 0;
9915
Sean Hunt49634cf2011-05-13 06:10:58 +00009916 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9917 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009918 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009919 if (Const)
9920 ArgType = ArgType.withConst();
9921 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009922
Richard Smith7756afa2012-06-10 05:43:50 +00009923 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9924 CXXCopyConstructor,
9925 Const);
9926
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009927 DeclarationName Name
9928 = Context.DeclarationNames.getCXXConstructorName(
9929 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009930 SourceLocation ClassLoc = ClassDecl->getLocation();
9931 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009932
9933 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009934 // member of its class.
9935 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009936 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009937 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009938 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009939 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009940 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009941
Richard Smithb9d0b762012-07-27 04:22:15 +00009942 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009943 FunctionProtoType::ExtProtoInfo EPI =
9944 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +00009945 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009946 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009947
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009948 // Add the parameter to the constructor.
9949 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009950 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009951 /*IdentifierInfo=*/0,
9952 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009953 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009954 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009955
Richard Smithbc2a35d2012-12-08 08:32:28 +00009956 CopyConstructor->setTrivial(
9957 ClassDecl->needsOverloadResolutionForCopyConstructor()
9958 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9959 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009960
Nico Weberafcc96a2012-01-23 03:19:29 +00009961 // C++11 [class.copy]p8:
9962 // ... If the class definition does not explicitly declare a copy
9963 // constructor, there is no user-declared move constructor, and there is no
9964 // user-declared move assignment operator, a copy constructor is implicitly
9965 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009966 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009967 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009968
Richard Smithbc2a35d2012-12-08 08:32:28 +00009969 // Note that we have declared this constructor.
9970 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9971
9972 if (Scope *S = getScopeForContext(ClassDecl))
9973 PushOnScopeChains(CopyConstructor, S, false);
9974 ClassDecl->addDecl(CopyConstructor);
9975
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009976 return CopyConstructor;
9977}
9978
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009979void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009980 CXXConstructorDecl *CopyConstructor) {
9981 assert((CopyConstructor->isDefaulted() &&
9982 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009983 !CopyConstructor->doesThisDeclarationHaveABody() &&
9984 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009985 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009986
Anders Carlsson63010a72010-04-23 16:24:12 +00009987 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009988 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009989
Richard Smith36155c12013-06-13 03:23:42 +00009990 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +00009991 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +00009992 // deprecated if the class has a user-declared copy assignment operator
9993 // or a user-declared destructor.
9994 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9995 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9996
Eli Friedman9a14db32012-10-18 20:14:08 +00009997 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009998 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009999
David Blaikie93c86172013-01-17 05:26:25 +000010000 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010001 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010002 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010003 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010004 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010005 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010006 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010007 CopyConstructor->setBody(ActOnCompoundStmt(
10008 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10009 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010010 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010011
Eli Friedman86164e82013-09-05 00:02:25 +000010012 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010013 if (ASTMutationListener *L = getASTMutationListener()) {
10014 L->CompletedImplicitDefinition(CopyConstructor);
10015 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010016}
10017
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010018Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010019Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10020 CXXRecordDecl *ClassDecl = MD->getParent();
10021
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010022 // C++ [except.spec]p14:
10023 // An implicitly declared special member function (Clause 12) shall have an
10024 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010025 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010026 if (ClassDecl->isInvalidDecl())
10027 return ExceptSpec;
10028
10029 // Direct base-class constructors.
10030 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10031 BEnd = ClassDecl->bases_end();
10032 B != BEnd; ++B) {
10033 if (B->isVirtual()) // Handled below.
10034 continue;
10035
10036 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10037 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010038 CXXConstructorDecl *Constructor =
10039 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010040 // If this is a deleted function, add it anyway. This might be conformant
10041 // with the standard. This might not. I'm not sure. It might not matter.
10042 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010043 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010044 }
10045 }
10046
10047 // Virtual base-class constructors.
10048 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10049 BEnd = ClassDecl->vbases_end();
10050 B != BEnd; ++B) {
10051 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10052 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010053 CXXConstructorDecl *Constructor =
10054 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010055 // If this is a deleted function, add it anyway. This might be conformant
10056 // with the standard. This might not. I'm not sure. It might not matter.
10057 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010058 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010059 }
10060 }
10061
10062 // Field constructors.
10063 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10064 FEnd = ClassDecl->field_end();
10065 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010066 QualType FieldType = Context.getBaseElementType(F->getType());
10067 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10068 CXXConstructorDecl *Constructor =
10069 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010070 // If this is a deleted function, add it anyway. This might be conformant
10071 // with the standard. This might not. I'm not sure. It might not matter.
10072 // In particular, the problem is that this function never gets called. It
10073 // might just be ill-formed because this function attempts to refer to
10074 // a deleted function here.
10075 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010076 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010077 }
10078 }
10079
10080 return ExceptSpec;
10081}
10082
10083CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10084 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010085 // C++11 [class.copy]p9:
10086 // If the definition of a class X does not explicitly declare a move
10087 // constructor, one will be implicitly declared as defaulted if and only if:
10088 //
10089 // - [first 4 bullets]
10090 assert(ClassDecl->needsImplicitMoveConstructor());
10091
Richard Smithafb49182012-11-29 01:34:07 +000010092 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10093 if (DSM.isAlreadyBeingDeclared())
10094 return 0;
10095
Richard Smith1c931be2012-04-02 18:40:40 +000010096 // [Checked after we build the declaration]
10097 // - the move assignment operator would not be implicitly defined as
10098 // deleted,
10099
10100 // [DR1402]:
10101 // - each of X's non-static data members and direct or virtual base classes
10102 // has a type that either has a move constructor or is trivially copyable.
10103 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10104 ClassDecl->setFailedImplicitMoveConstructor();
10105 return 0;
10106 }
10107
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010108 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10109 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010110
Richard Smith7756afa2012-06-10 05:43:50 +000010111 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10112 CXXMoveConstructor,
10113 false);
10114
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010115 DeclarationName Name
10116 = Context.DeclarationNames.getCXXConstructorName(
10117 Context.getCanonicalType(ClassType));
10118 SourceLocation ClassLoc = ClassDecl->getLocation();
10119 DeclarationNameInfo NameInfo(Name, ClassLoc);
10120
Richard Smitha8942d72013-05-07 03:19:20 +000010121 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010122 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010123 // member of its class.
10124 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010125 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010126 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010127 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010128 MoveConstructor->setAccess(AS_public);
10129 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010130
Richard Smithb9d0b762012-07-27 04:22:15 +000010131 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010132 FunctionProtoType::ExtProtoInfo EPI =
10133 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010134 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010135 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010136
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010137 // Add the parameter to the constructor.
10138 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10139 ClassLoc, ClassLoc,
10140 /*IdentifierInfo=*/0,
10141 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010142 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010143 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010144
Richard Smithbc2a35d2012-12-08 08:32:28 +000010145 MoveConstructor->setTrivial(
10146 ClassDecl->needsOverloadResolutionForMoveConstructor()
10147 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10148 : ClassDecl->hasTrivialMoveConstructor());
10149
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010150 // C++0x [class.copy]p9:
10151 // If the definition of a class X does not explicitly declare a move
10152 // constructor, one will be implicitly declared as defaulted if and only if:
10153 // [...]
10154 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010155 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010156 // Cache this result so that we don't try to generate this over and over
10157 // on every lookup, leaking memory and wasting time.
10158 ClassDecl->setFailedImplicitMoveConstructor();
10159 return 0;
10160 }
10161
10162 // Note that we have declared this constructor.
10163 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10164
10165 if (Scope *S = getScopeForContext(ClassDecl))
10166 PushOnScopeChains(MoveConstructor, S, false);
10167 ClassDecl->addDecl(MoveConstructor);
10168
10169 return MoveConstructor;
10170}
10171
10172void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10173 CXXConstructorDecl *MoveConstructor) {
10174 assert((MoveConstructor->isDefaulted() &&
10175 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010176 !MoveConstructor->doesThisDeclarationHaveABody() &&
10177 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010178 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10179
10180 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10181 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10182
Eli Friedman9a14db32012-10-18 20:14:08 +000010183 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010184 DiagnosticErrorTrap Trap(Diags);
10185
David Blaikie93c86172013-01-17 05:26:25 +000010186 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010187 Trap.hasErrorOccurred()) {
10188 Diag(CurrentLocation, diag::note_member_synthesized_at)
10189 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10190 MoveConstructor->setInvalidDecl();
10191 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010192 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010193 MoveConstructor->setBody(ActOnCompoundStmt(
10194 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10195 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010196 }
10197
Eli Friedman86164e82013-09-05 00:02:25 +000010198 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010199
10200 if (ASTMutationListener *L = getASTMutationListener()) {
10201 L->CompletedImplicitDefinition(MoveConstructor);
10202 }
10203}
10204
Douglas Gregore4e68d42012-02-15 19:33:52 +000010205bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010206 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010207}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010208
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010209/// \brief Mark the call operator of the given lambda closure type as "used".
10210static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10211 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010212 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010213 Lambda->lookup(
10214 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010215 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +000010216 CallOperator->markUsed(S.Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010217}
10218
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010219void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10220 SourceLocation CurrentLocation,
10221 CXXConversionDecl *Conv)
10222{
Manuel Klimek152b4e42013-08-22 12:12:24 +000010223 CXXRecordDecl *Lambda = Conv->getParent();
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010224
10225 // Make sure that the lambda call operator is marked used.
Manuel Klimek152b4e42013-08-22 12:12:24 +000010226 markLambdaCallOperatorUsed(*this, Lambda);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010227
Eli Friedman86164e82013-09-05 00:02:25 +000010228 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010229
Eli Friedman9a14db32012-10-18 20:14:08 +000010230 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010231 DiagnosticErrorTrap Trap(Diags);
10232
Manuel Klimek152b4e42013-08-22 12:12:24 +000010233 // Return the address of the __invoke function.
10234 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10235 CXXMethodDecl *Invoke
10236 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010237 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10238 VK_LValue, Conv->getLocation()).take();
Manuel Klimek152b4e42013-08-22 12:12:24 +000010239 assert(FunctionRef && "Can't refer to __invoke function?");
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010240 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010241 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010242 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010243 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010244
Manuel Klimek152b4e42013-08-22 12:12:24 +000010245 // Fill in the __invoke function with a dummy implementation. IR generation
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010246 // will fill in the actual details.
Eli Friedman86164e82013-09-05 00:02:25 +000010247 Invoke->markUsed(Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010248 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010249 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010250
10251 if (ASTMutationListener *L = getASTMutationListener()) {
10252 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010253 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010254 }
10255}
10256
10257void Sema::DefineImplicitLambdaToBlockPointerConversion(
10258 SourceLocation CurrentLocation,
10259 CXXConversionDecl *Conv)
10260{
Eli Friedman86164e82013-09-05 00:02:25 +000010261 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010262
Eli Friedman9a14db32012-10-18 20:14:08 +000010263 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010264 DiagnosticErrorTrap Trap(Diags);
10265
Douglas Gregorac1303e2012-02-22 05:02:47 +000010266 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010267 Expr *This = ActOnCXXThis(CurrentLocation).take();
10268 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010269
Eli Friedman23f02672012-03-01 04:01:32 +000010270 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10271 Conv->getLocation(),
10272 Conv, DerefThis);
10273
10274 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10275 // behavior. Note that only the general conversion function does this
10276 // (since it's unusable otherwise); in the case where we inline the
10277 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010278 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010279 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10280 CK_CopyAndAutoreleaseBlockObject,
10281 BuildBlock.get(), 0, VK_RValue);
10282
10283 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010284 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010285 Conv->setInvalidDecl();
10286 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010287 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010288
Douglas Gregorac1303e2012-02-22 05:02:47 +000010289 // Create the return statement that returns the block from the conversion
10290 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010291 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010292 if (Return.isInvalid()) {
10293 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10294 Conv->setInvalidDecl();
10295 return;
10296 }
10297
10298 // Set the body of the conversion function.
10299 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010300 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010301 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010302 Conv->getLocation()));
10303
Douglas Gregorac1303e2012-02-22 05:02:47 +000010304 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010305 if (ASTMutationListener *L = getASTMutationListener()) {
10306 L->CompletedImplicitDefinition(Conv);
10307 }
10308}
10309
Douglas Gregorf52757d2012-03-10 06:53:13 +000010310/// \brief Determine whether the given list arguments contains exactly one
10311/// "real" (non-default) argument.
10312static bool hasOneRealArgument(MultiExprArg Args) {
10313 switch (Args.size()) {
10314 case 0:
10315 return false;
10316
10317 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010318 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010319 return false;
10320
10321 // fall through
10322 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010323 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010324 }
10325
10326 return false;
10327}
10328
John McCall60d7b3a2010-08-24 06:29:42 +000010329ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010330Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010331 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010332 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010333 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010334 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010335 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010336 unsigned ConstructKind,
10337 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010338 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010339
Douglas Gregor2f599792010-04-02 18:24:57 +000010340 // C++0x [class.copy]p34:
10341 // When certain criteria are met, an implementation is allowed to
10342 // omit the copy/move construction of a class object, even if the
10343 // copy/move constructor and/or destructor for the object have
10344 // side effects. [...]
10345 // - when a temporary class object that has not been bound to a
10346 // reference (12.2) would be copied/moved to a class object
10347 // with the same cv-unqualified type, the copy/move operation
10348 // can be omitted by constructing the temporary object
10349 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010350 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010351 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010352 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010353 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010354 }
Mike Stump1eb44332009-09-09 15:08:12 +000010355
10356 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010357 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010358 IsListInitialization, RequiresZeroInit,
10359 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010360}
10361
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010362/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10363/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010364ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010365Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10366 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010367 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010368 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010369 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010370 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010371 unsigned ConstructKind,
10372 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010373 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010374 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010375 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010376 HadMultipleCandidates,
10377 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010378 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10379 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010380}
10381
John McCall68c6c9a2010-02-02 09:10:11 +000010382void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010383 if (VD->isInvalidDecl()) return;
10384
John McCall68c6c9a2010-02-02 09:10:11 +000010385 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010386 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010387 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010388 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010389
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010390 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010391 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010392 CheckDestructorAccess(VD->getLocation(), Destructor,
10393 PDiag(diag::err_access_dtor_var)
10394 << VD->getDeclName()
10395 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010396 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010397
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010398 if (!VD->hasGlobalStorage()) return;
10399
10400 // Emit warning for non-trivial dtor in global scope (a real global,
10401 // class-static, function-static).
10402 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10403
10404 // TODO: this should be re-enabled for static locals by !CXAAtExit
10405 if (!VD->isStaticLocal())
10406 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010407}
10408
Douglas Gregor39da0b82009-09-09 23:08:42 +000010409/// \brief Given a constructor and the set of arguments provided for the
10410/// constructor, convert the arguments and add any required default arguments
10411/// to form a proper call to this constructor.
10412///
10413/// \returns true if an error occurred, false otherwise.
10414bool
10415Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10416 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010417 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010418 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010419 bool AllowExplicit,
10420 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010421 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10422 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010423 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010424
10425 const FunctionProtoType *Proto
10426 = Constructor->getType()->getAs<FunctionProtoType>();
10427 assert(Proto && "Constructor without a prototype?");
10428 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010429
10430 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010431 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010432 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010433 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010434 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010435
10436 VariadicCallType CallType =
10437 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010438 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010439 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010440 Proto, 0,
10441 llvm::makeArrayRef(Args, NumArgs),
10442 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010443 CallType, AllowExplicit,
10444 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010445 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010446
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010447 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010448
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010449 CheckConstructorCall(Constructor,
10450 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10451 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010452 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010453
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010454 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010455}
10456
Anders Carlsson20d45d22009-12-12 00:32:00 +000010457static inline bool
10458CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10459 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010460 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010461 if (isa<NamespaceDecl>(DC)) {
10462 return SemaRef.Diag(FnDecl->getLocation(),
10463 diag::err_operator_new_delete_declared_in_namespace)
10464 << FnDecl->getDeclName();
10465 }
10466
10467 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010468 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010469 return SemaRef.Diag(FnDecl->getLocation(),
10470 diag::err_operator_new_delete_declared_static)
10471 << FnDecl->getDeclName();
10472 }
10473
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010474 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010475}
10476
Anders Carlsson156c78e2009-12-13 17:53:43 +000010477static inline bool
10478CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10479 CanQualType ExpectedResultType,
10480 CanQualType ExpectedFirstParamType,
10481 unsigned DependentParamTypeDiag,
10482 unsigned InvalidParamTypeDiag) {
10483 QualType ResultType =
10484 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10485
10486 // Check that the result type is not dependent.
10487 if (ResultType->isDependentType())
10488 return SemaRef.Diag(FnDecl->getLocation(),
10489 diag::err_operator_new_delete_dependent_result_type)
10490 << FnDecl->getDeclName() << ExpectedResultType;
10491
10492 // Check that the result type is what we expect.
10493 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10494 return SemaRef.Diag(FnDecl->getLocation(),
10495 diag::err_operator_new_delete_invalid_result_type)
10496 << FnDecl->getDeclName() << ExpectedResultType;
10497
10498 // A function template must have at least 2 parameters.
10499 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10500 return SemaRef.Diag(FnDecl->getLocation(),
10501 diag::err_operator_new_delete_template_too_few_parameters)
10502 << FnDecl->getDeclName();
10503
10504 // The function decl must have at least 1 parameter.
10505 if (FnDecl->getNumParams() == 0)
10506 return SemaRef.Diag(FnDecl->getLocation(),
10507 diag::err_operator_new_delete_too_few_parameters)
10508 << FnDecl->getDeclName();
10509
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010510 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010511 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10512 if (FirstParamType->isDependentType())
10513 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10514 << FnDecl->getDeclName() << ExpectedFirstParamType;
10515
10516 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010517 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010518 ExpectedFirstParamType)
10519 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10520 << FnDecl->getDeclName() << ExpectedFirstParamType;
10521
10522 return false;
10523}
10524
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010525static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010526CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010527 // C++ [basic.stc.dynamic.allocation]p1:
10528 // A program is ill-formed if an allocation function is declared in a
10529 // namespace scope other than global scope or declared static in global
10530 // scope.
10531 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10532 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010533
10534 CanQualType SizeTy =
10535 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10536
10537 // C++ [basic.stc.dynamic.allocation]p1:
10538 // The return type shall be void*. The first parameter shall have type
10539 // std::size_t.
10540 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10541 SizeTy,
10542 diag::err_operator_new_dependent_param_type,
10543 diag::err_operator_new_param_type))
10544 return true;
10545
10546 // C++ [basic.stc.dynamic.allocation]p1:
10547 // The first parameter shall not have an associated default argument.
10548 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010549 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010550 diag::err_operator_new_default_arg)
10551 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10552
10553 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010554}
10555
10556static bool
Richard Smith444d3842012-10-20 08:26:51 +000010557CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010558 // C++ [basic.stc.dynamic.deallocation]p1:
10559 // A program is ill-formed if deallocation functions are declared in a
10560 // namespace scope other than global scope or declared static in global
10561 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010562 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10563 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010564
10565 // C++ [basic.stc.dynamic.deallocation]p2:
10566 // Each deallocation function shall return void and its first parameter
10567 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010568 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10569 SemaRef.Context.VoidPtrTy,
10570 diag::err_operator_delete_dependent_param_type,
10571 diag::err_operator_delete_param_type))
10572 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010573
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010574 return false;
10575}
10576
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010577/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10578/// of this overloaded operator is well-formed. If so, returns false;
10579/// otherwise, emits appropriate diagnostics and returns true.
10580bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010581 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010582 "Expected an overloaded operator declaration");
10583
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010584 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10585
Mike Stump1eb44332009-09-09 15:08:12 +000010586 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010587 // The allocation and deallocation functions, operator new,
10588 // operator new[], operator delete and operator delete[], are
10589 // described completely in 3.7.3. The attributes and restrictions
10590 // found in the rest of this subclause do not apply to them unless
10591 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010592 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010593 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010594
Anders Carlssona3ccda52009-12-12 00:26:23 +000010595 if (Op == OO_New || Op == OO_Array_New)
10596 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010597
10598 // C++ [over.oper]p6:
10599 // An operator function shall either be a non-static member
10600 // function or be a non-member function and have at least one
10601 // parameter whose type is a class, a reference to a class, an
10602 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010603 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10604 if (MethodDecl->isStatic())
10605 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010606 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010607 } else {
10608 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010609 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10610 ParamEnd = FnDecl->param_end();
10611 Param != ParamEnd; ++Param) {
10612 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010613 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10614 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010615 ClassOrEnumParam = true;
10616 break;
10617 }
10618 }
10619
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010620 if (!ClassOrEnumParam)
10621 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010622 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010623 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010624 }
10625
10626 // C++ [over.oper]p8:
10627 // An operator function cannot have default arguments (8.3.6),
10628 // except where explicitly stated below.
10629 //
Mike Stump1eb44332009-09-09 15:08:12 +000010630 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010631 // (C++ [over.call]p1).
10632 if (Op != OO_Call) {
10633 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10634 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010635 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010636 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010637 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010638 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010639 }
10640 }
10641
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010642 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10643 { false, false, false }
10644#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10645 , { Unary, Binary, MemberOnly }
10646#include "clang/Basic/OperatorKinds.def"
10647 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010648
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010649 bool CanBeUnaryOperator = OperatorUses[Op][0];
10650 bool CanBeBinaryOperator = OperatorUses[Op][1];
10651 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010652
10653 // C++ [over.oper]p8:
10654 // [...] Operator functions cannot have more or fewer parameters
10655 // than the number required for the corresponding operator, as
10656 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010657 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010658 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010659 if (Op != OO_Call &&
10660 ((NumParams == 1 && !CanBeUnaryOperator) ||
10661 (NumParams == 2 && !CanBeBinaryOperator) ||
10662 (NumParams < 1) || (NumParams > 2))) {
10663 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010664 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010665 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010666 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010667 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010668 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010669 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010670 assert(CanBeBinaryOperator &&
10671 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010672 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010673 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010674
Chris Lattner416e46f2008-11-21 07:57:12 +000010675 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010676 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010677 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010678
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010679 // Overloaded operators other than operator() cannot be variadic.
10680 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010681 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010682 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010683 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010684 }
10685
10686 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010687 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10688 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010689 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010690 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010691 }
10692
10693 // C++ [over.inc]p1:
10694 // The user-defined function called operator++ implements the
10695 // prefix and postfix ++ operator. If this function is a member
10696 // function with no parameters, or a non-member function with one
10697 // parameter of class or enumeration type, it defines the prefix
10698 // increment operator ++ for objects of that type. If the function
10699 // is a member function with one parameter (which shall be of type
10700 // int) or a non-member function with two parameters (the second
10701 // of which shall be of type int), it defines the postfix
10702 // increment operator ++ for objects of that type.
10703 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10704 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10705 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010706 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010707 ParamIsInt = BT->getKind() == BuiltinType::Int;
10708
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010709 if (!ParamIsInt)
10710 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010711 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010712 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010713 }
10714
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010715 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010716}
Chris Lattner5a003a42008-12-17 07:09:26 +000010717
Sean Hunta6c058d2010-01-13 09:01:02 +000010718/// CheckLiteralOperatorDeclaration - Check whether the declaration
10719/// of this literal operator function is well-formed. If so, returns
10720/// false; otherwise, emits appropriate diagnostics and returns true.
10721bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010722 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010723 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10724 << FnDecl->getDeclName();
10725 return true;
10726 }
10727
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010728 if (FnDecl->isExternC()) {
10729 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10730 return true;
10731 }
10732
Sean Hunta6c058d2010-01-13 09:01:02 +000010733 bool Valid = false;
10734
Richard Smith36f5cfe2012-03-09 08:00:36 +000010735 // This might be the definition of a literal operator template.
10736 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10737 // This might be a specialization of a literal operator template.
10738 if (!TpDecl)
10739 TpDecl = FnDecl->getPrimaryTemplate();
10740
Sean Hunt216c2782010-04-07 23:11:06 +000010741 // template <char...> type operator "" name() is the only valid template
10742 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010743 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010744 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010745 // Must have only one template parameter
10746 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10747 if (Params->size() == 1) {
10748 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010749 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010750
Sean Hunt216c2782010-04-07 23:11:06 +000010751 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010752 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10753 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10754 Valid = true;
10755 }
10756 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010757 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010758 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010759 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10760
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010761 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010762
Sean Hunt30019c02010-04-07 22:57:35 +000010763 // unsigned long long int, long double, and any character type are allowed
10764 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010765 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10766 Context.hasSameType(T, Context.LongDoubleTy) ||
10767 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010768 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010769 Context.hasSameType(T, Context.Char16Ty) ||
10770 Context.hasSameType(T, Context.Char32Ty)) {
10771 if (++Param == FnDecl->param_end())
10772 Valid = true;
10773 goto FinishedParams;
10774 }
10775
Sean Hunt30019c02010-04-07 22:57:35 +000010776 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010777 const PointerType *PT = T->getAs<PointerType>();
10778 if (!PT)
10779 goto FinishedParams;
10780 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010781 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010782 goto FinishedParams;
10783 T = T.getUnqualifiedType();
10784
10785 // Move on to the second parameter;
10786 ++Param;
10787
10788 // If there is no second parameter, the first must be a const char *
10789 if (Param == FnDecl->param_end()) {
10790 if (Context.hasSameType(T, Context.CharTy))
10791 Valid = true;
10792 goto FinishedParams;
10793 }
10794
10795 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10796 // are allowed as the first parameter to a two-parameter function
10797 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010798 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010799 Context.hasSameType(T, Context.Char16Ty) ||
10800 Context.hasSameType(T, Context.Char32Ty)))
10801 goto FinishedParams;
10802
10803 // The second and final parameter must be an std::size_t
10804 T = (*Param)->getType().getUnqualifiedType();
10805 if (Context.hasSameType(T, Context.getSizeType()) &&
10806 ++Param == FnDecl->param_end())
10807 Valid = true;
10808 }
10809
10810 // FIXME: This diagnostic is absolutely terrible.
10811FinishedParams:
10812 if (!Valid) {
10813 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10814 << FnDecl->getDeclName();
10815 return true;
10816 }
10817
Richard Smitha9e88b22012-03-09 08:16:22 +000010818 // A parameter-declaration-clause containing a default argument is not
10819 // equivalent to any of the permitted forms.
10820 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10821 ParamEnd = FnDecl->param_end();
10822 Param != ParamEnd; ++Param) {
10823 if ((*Param)->hasDefaultArg()) {
10824 Diag((*Param)->getDefaultArgRange().getBegin(),
10825 diag::err_literal_operator_default_argument)
10826 << (*Param)->getDefaultArgRange();
10827 break;
10828 }
10829 }
10830
Richard Smith2fb4ae32012-03-08 02:39:21 +000010831 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010832 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10833 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010834 // C++11 [usrlit.suffix]p1:
10835 // Literal suffix identifiers that do not start with an underscore
10836 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010837 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10838 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010839 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010840
Sean Hunta6c058d2010-01-13 09:01:02 +000010841 return false;
10842}
10843
Douglas Gregor074149e2009-01-05 19:45:36 +000010844/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10845/// linkage specification, including the language and (if present)
10846/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10847/// the location of the language string literal, which is provided
10848/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10849/// the '{' brace. Otherwise, this linkage specification does not
10850/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010851Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10852 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010853 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010854 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010855 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010856 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010857 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010858 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010859 Language = LinkageSpecDecl::lang_cxx;
10860 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010861 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010862 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010863 }
Mike Stump1eb44332009-09-09 15:08:12 +000010864
Chris Lattnercc98eac2008-12-17 07:13:27 +000010865 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010866
Douglas Gregor074149e2009-01-05 19:45:36 +000010867 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010868 ExternLoc, LangLoc, Language,
10869 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010870 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010871 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010872 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010873}
10874
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010875/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010876/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10877/// valid, it's the position of the closing '}' brace in a linkage
10878/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010879Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010880 Decl *LinkageSpec,
10881 SourceLocation RBraceLoc) {
10882 if (LinkageSpec) {
10883 if (RBraceLoc.isValid()) {
10884 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10885 LSDecl->setRBraceLoc(RBraceLoc);
10886 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010887 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010888 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010889 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010890}
10891
Michael Han684aa732013-02-22 17:15:32 +000010892Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10893 AttributeList *AttrList,
10894 SourceLocation SemiLoc) {
10895 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10896 // Attribute declarations appertain to empty declaration so we handle
10897 // them here.
10898 if (AttrList)
10899 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010900
Michael Han684aa732013-02-22 17:15:32 +000010901 CurContext->addDecl(ED);
10902 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010903}
10904
Douglas Gregord308e622009-05-18 20:51:54 +000010905/// \brief Perform semantic analysis for the variable declaration that
10906/// occurs within a C++ catch clause, returning the newly-created
10907/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010908VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010909 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010910 SourceLocation StartLoc,
10911 SourceLocation Loc,
10912 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010913 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010914 QualType ExDeclType = TInfo->getType();
10915
Sebastian Redl4b07b292008-12-22 19:15:10 +000010916 // Arrays and functions decay.
10917 if (ExDeclType->isArrayType())
10918 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10919 else if (ExDeclType->isFunctionType())
10920 ExDeclType = Context.getPointerType(ExDeclType);
10921
10922 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10923 // The exception-declaration shall not denote a pointer or reference to an
10924 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010925 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010926 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010927 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010928 Invalid = true;
10929 }
Douglas Gregord308e622009-05-18 20:51:54 +000010930
Sebastian Redl4b07b292008-12-22 19:15:10 +000010931 QualType BaseType = ExDeclType;
10932 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010933 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010934 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010935 BaseType = Ptr->getPointeeType();
10936 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010937 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010938 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010939 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010940 BaseType = Ref->getPointeeType();
10941 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010942 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010943 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010944 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010945 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010946 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010947
Mike Stump1eb44332009-09-09 15:08:12 +000010948 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010949 RequireNonAbstractType(Loc, ExDeclType,
10950 diag::err_abstract_type_in_decl,
10951 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010952 Invalid = true;
10953
John McCall5a180392010-07-24 00:37:23 +000010954 // Only the non-fragile NeXT runtime currently supports C++ catches
10955 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010956 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010957 QualType T = ExDeclType;
10958 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10959 T = RT->getPointeeType();
10960
10961 if (T->isObjCObjectType()) {
10962 Diag(Loc, diag::err_objc_object_catch);
10963 Invalid = true;
10964 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010965 // FIXME: should this be a test for macosx-fragile specifically?
10966 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010967 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010968 }
10969 }
10970
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010971 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010972 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010973 ExDecl->setExceptionVariable(true);
10974
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010975 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010976 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010977 Invalid = true;
10978
Douglas Gregorc41b8782011-07-06 18:14:43 +000010979 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010980 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010981 // Insulate this from anything else we might currently be parsing.
10982 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10983
Douglas Gregor6d182892010-03-05 23:38:39 +000010984 // C++ [except.handle]p16:
10985 // The object declared in an exception-declaration or, if the
10986 // exception-declaration does not specify a name, a temporary (12.2) is
10987 // copy-initialized (8.5) from the exception object. [...]
10988 // The object is destroyed when the handler exits, after the destruction
10989 // of any automatic objects initialized within the handler.
10990 //
10991 // We just pretend to initialize the object with itself, then make sure
10992 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010993 QualType initType = ExDeclType;
10994
10995 InitializedEntity entity =
10996 InitializedEntity::InitializeVariable(ExDecl);
10997 InitializationKind initKind =
10998 InitializationKind::CreateCopy(Loc, SourceLocation());
10999
11000 Expr *opaqueValue =
11001 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011002 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11003 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011004 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011005 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011006 else {
11007 // If the constructor used was non-trivial, set this as the
11008 // "initializer".
11009 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
11010 if (!construct->getConstructor()->isTrivial()) {
11011 Expr *init = MaybeCreateExprWithCleanups(construct);
11012 ExDecl->setInit(init);
11013 }
11014
11015 // And make sure it's destructable.
11016 FinalizeVarWithDestructor(ExDecl, recordType);
11017 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011018 }
11019 }
11020
Douglas Gregord308e622009-05-18 20:51:54 +000011021 if (Invalid)
11022 ExDecl->setInvalidDecl();
11023
11024 return ExDecl;
11025}
11026
11027/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11028/// handler.
John McCalld226f652010-08-21 09:40:31 +000011029Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011030 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011031 bool Invalid = D.isInvalidType();
11032
11033 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011034 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11035 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011036 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11037 D.getIdentifierLoc());
11038 Invalid = true;
11039 }
11040
Sebastian Redl4b07b292008-12-22 19:15:10 +000011041 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011042 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011043 LookupOrdinaryName,
11044 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011045 // The scope should be freshly made just for us. There is just no way
11046 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011047 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011048 if (PrevDecl->isTemplateParameter()) {
11049 // Maybe we will complain about the shadowed template parameter.
11050 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011051 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011052 }
11053 }
11054
Chris Lattnereaaebc72009-04-25 08:06:05 +000011055 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011056 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11057 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011058 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011059 }
11060
Douglas Gregor83cb9422010-09-09 17:09:21 +000011061 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011062 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011063 D.getIdentifierLoc(),
11064 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011065 if (Invalid)
11066 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011067
Sebastian Redl4b07b292008-12-22 19:15:10 +000011068 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011069 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011070 PushOnScopeChains(ExDecl, S);
11071 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011072 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011073
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011074 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011075 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011076}
Anders Carlssonfb311762009-03-14 00:25:26 +000011077
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011078Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011079 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011080 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011081 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011082 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011083
Richard Smithe3f470a2012-07-11 22:37:56 +000011084 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11085 return 0;
11086
11087 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11088 AssertMessage, RParenLoc, false);
11089}
11090
11091Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11092 Expr *AssertExpr,
11093 StringLiteral *AssertMessage,
11094 SourceLocation RParenLoc,
11095 bool Failed) {
11096 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11097 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011098 // In a static_assert-declaration, the constant-expression shall be a
11099 // constant expression that can be contextually converted to bool.
11100 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11101 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011102 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011103
Richard Smithdaaefc52011-12-14 23:32:26 +000011104 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011105 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011106 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011107 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011108 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011109
Richard Smithe3f470a2012-07-11 22:37:56 +000011110 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011111 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011112 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011113 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011114 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011115 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011116 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011117 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011118 }
Mike Stump1eb44332009-09-09 15:08:12 +000011119
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011120 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011121 AssertExpr, AssertMessage, RParenLoc,
11122 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011123
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011124 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011125 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011126}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011127
Douglas Gregor1d869352010-04-07 16:53:43 +000011128/// \brief Perform semantic analysis of the given friend type declaration.
11129///
11130/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011131FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011132 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011133 TypeSourceInfo *TSInfo) {
11134 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11135
11136 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011137 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011138
Richard Smith6b130222011-10-18 21:39:00 +000011139 // C++03 [class.friend]p2:
11140 // An elaborated-type-specifier shall be used in a friend declaration
11141 // for a class.*
11142 //
11143 // * The class-key of the elaborated-type-specifier is required.
11144 if (!ActiveTemplateInstantiations.empty()) {
11145 // Do not complain about the form of friend template types during
11146 // template instantiation; we will already have complained when the
11147 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011148 } else {
11149 if (!T->isElaboratedTypeSpecifier()) {
11150 // If we evaluated the type to a record type, suggest putting
11151 // a tag in front.
11152 if (const RecordType *RT = T->getAs<RecordType>()) {
11153 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011154
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011155 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011156
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011157 Diag(TypeRange.getBegin(),
11158 getLangOpts().CPlusPlus11 ?
11159 diag::warn_cxx98_compat_unelaborated_friend_type :
11160 diag::ext_unelaborated_friend_type)
11161 << (unsigned) RD->getTagKind()
11162 << T
11163 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11164 InsertionText);
11165 } else {
11166 Diag(FriendLoc,
11167 getLangOpts().CPlusPlus11 ?
11168 diag::warn_cxx98_compat_nonclass_type_friend :
11169 diag::ext_nonclass_type_friend)
11170 << T
11171 << TypeRange;
11172 }
11173 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011174 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011175 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011176 diag::warn_cxx98_compat_enum_friend :
11177 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011178 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011179 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011180 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011181
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011182 // C++11 [class.friend]p3:
11183 // A friend declaration that does not declare a function shall have one
11184 // of the following forms:
11185 // friend elaborated-type-specifier ;
11186 // friend simple-type-specifier ;
11187 // friend typename-specifier ;
11188 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11189 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11190 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011191
Douglas Gregor06245bf2010-04-07 17:57:12 +000011192 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011193 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011194 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011195 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011196}
11197
John McCall9a34edb2010-10-19 01:40:49 +000011198/// Handle a friend tag declaration where the scope specifier was
11199/// templated.
11200Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11201 unsigned TagSpec, SourceLocation TagLoc,
11202 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011203 IdentifierInfo *Name,
11204 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011205 AttributeList *Attr,
11206 MultiTemplateParamsArg TempParamLists) {
11207 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11208
11209 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011210 bool Invalid = false;
11211
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011212 if (TemplateParameterList *TemplateParams =
11213 MatchTemplateParametersToScopeSpecifier(
11214 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11215 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011216 if (TemplateParams->size() > 0) {
11217 // This is a declaration of a class template.
11218 if (Invalid)
11219 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011220
Eric Christopher4110e132011-07-21 05:34:24 +000011221 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11222 SS, Name, NameLoc, Attr,
11223 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011224 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011225 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011226 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011227 } else {
11228 // The "template<>" header is extraneous.
11229 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11230 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11231 isExplicitSpecialization = true;
11232 }
11233 }
11234
11235 if (Invalid) return 0;
11236
John McCall9a34edb2010-10-19 01:40:49 +000011237 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011238 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011239 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011240 isAllExplicitSpecializations = false;
11241 break;
11242 }
11243 }
11244
11245 // FIXME: don't ignore attributes.
11246
11247 // If it's explicit specializations all the way down, just forget
11248 // about the template header and build an appropriate non-templated
11249 // friend. TODO: for source fidelity, remember the headers.
11250 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011251 if (SS.isEmpty()) {
11252 bool Owned = false;
11253 bool IsDependent = false;
11254 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11255 Attr, AS_public,
11256 /*ModulePrivateLoc=*/SourceLocation(),
11257 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011258 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011259 /*ScopedEnumUsesClassTag=*/false,
11260 /*UnderlyingType=*/TypeResult());
11261 }
11262
Douglas Gregor2494dd02011-03-01 01:34:45 +000011263 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011264 ElaboratedTypeKeyword Keyword
11265 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011266 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011267 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011268 if (T.isNull())
11269 return 0;
11270
11271 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11272 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011273 DependentNameTypeLoc TL =
11274 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011275 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011276 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011277 TL.setNameLoc(NameLoc);
11278 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011279 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011280 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011281 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011282 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011283 }
11284
11285 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011286 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011287 Friend->setAccess(AS_public);
11288 CurContext->addDecl(Friend);
11289 return Friend;
11290 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011291
11292 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11293
11294
John McCall9a34edb2010-10-19 01:40:49 +000011295
11296 // Handle the case of a templated-scope friend class. e.g.
11297 // template <class T> class A<T>::B;
11298 // FIXME: we don't support these right now.
11299 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11300 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11301 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011302 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011303 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011304 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011305 TL.setNameLoc(NameLoc);
11306
11307 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011308 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011309 Friend->setAccess(AS_public);
11310 Friend->setUnsupportedFriend(true);
11311 CurContext->addDecl(Friend);
11312 return Friend;
11313}
11314
11315
John McCalldd4a3b02009-09-16 22:47:08 +000011316/// Handle a friend type declaration. This works in tandem with
11317/// ActOnTag.
11318///
11319/// Notes on friend class templates:
11320///
11321/// We generally treat friend class declarations as if they were
11322/// declaring a class. So, for example, the elaborated type specifier
11323/// in a friend declaration is required to obey the restrictions of a
11324/// class-head (i.e. no typedefs in the scope chain), template
11325/// parameters are required to match up with simple template-ids, &c.
11326/// However, unlike when declaring a template specialization, it's
11327/// okay to refer to a template specialization without an empty
11328/// template parameter declaration, e.g.
11329/// friend class A<T>::B<unsigned>;
11330/// We permit this as a special case; if there are any template
11331/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011332/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011333Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011334 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011335 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011336
11337 assert(DS.isFriendSpecified());
11338 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11339
John McCalldd4a3b02009-09-16 22:47:08 +000011340 // Try to convert the decl specifier to a type. This works for
11341 // friend templates because ActOnTag never produces a ClassTemplateDecl
11342 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011343 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011344 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11345 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011346 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011347 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011348
Douglas Gregor6ccab972010-12-16 01:14:37 +000011349 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11350 return 0;
11351
John McCalldd4a3b02009-09-16 22:47:08 +000011352 // This is definitely an error in C++98. It's probably meant to
11353 // be forbidden in C++0x, too, but the specification is just
11354 // poorly written.
11355 //
11356 // The problem is with declarations like the following:
11357 // template <T> friend A<T>::foo;
11358 // where deciding whether a class C is a friend or not now hinges
11359 // on whether there exists an instantiation of A that causes
11360 // 'foo' to equal C. There are restrictions on class-heads
11361 // (which we declare (by fiat) elaborated friend declarations to
11362 // be) that makes this tractable.
11363 //
11364 // FIXME: handle "template <> friend class A<T>;", which
11365 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011366 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011367 Diag(Loc, diag::err_tagless_friend_type_template)
11368 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011369 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011370 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011371
John McCall02cace72009-08-28 07:59:38 +000011372 // C++98 [class.friend]p1: A friend of a class is a function
11373 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011374 // This is fixed in DR77, which just barely didn't make the C++03
11375 // deadline. It's also a very silly restriction that seriously
11376 // affects inner classes and which nobody else seems to implement;
11377 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011378 //
11379 // But note that we could warn about it: it's always useless to
11380 // friend one of your own members (it's not, however, worthless to
11381 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011382
John McCalldd4a3b02009-09-16 22:47:08 +000011383 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011384 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011385 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011386 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011387 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011388 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011389 DS.getFriendSpecLoc());
11390 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011391 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011392
11393 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011394 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011395
John McCalldd4a3b02009-09-16 22:47:08 +000011396 D->setAccess(AS_public);
11397 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011398
John McCalld226f652010-08-21 09:40:31 +000011399 return D;
John McCall02cace72009-08-28 07:59:38 +000011400}
11401
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011402NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11403 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011404 const DeclSpec &DS = D.getDeclSpec();
11405
11406 assert(DS.isFriendSpecified());
11407 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11408
11409 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011410 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011411
11412 // C++ [class.friend]p1
11413 // A friend of a class is a function or class....
11414 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011415 // It *doesn't* see through dependent types, which is correct
11416 // according to [temp.arg.type]p3:
11417 // If a declaration acquires a function type through a
11418 // type dependent on a template-parameter and this causes
11419 // a declaration that does not use the syntactic form of a
11420 // function declarator to have a function type, the program
11421 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011422 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011423 Diag(Loc, diag::err_unexpected_friend);
11424
11425 // It might be worthwhile to try to recover by creating an
11426 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011427 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011428 }
11429
11430 // C++ [namespace.memdef]p3
11431 // - If a friend declaration in a non-local class first declares a
11432 // class or function, the friend class or function is a member
11433 // of the innermost enclosing namespace.
11434 // - The name of the friend is not found by simple name lookup
11435 // until a matching declaration is provided in that namespace
11436 // scope (either before or after the class declaration granting
11437 // friendship).
11438 // - If a friend function is called, its name may be found by the
11439 // name lookup that considers functions from namespaces and
11440 // classes associated with the types of the function arguments.
11441 // - When looking for a prior declaration of a class or a function
11442 // declared as a friend, scopes outside the innermost enclosing
11443 // namespace scope are not considered.
11444
John McCall337ec3d2010-10-12 23:13:28 +000011445 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011446 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11447 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011448 assert(Name);
11449
Douglas Gregor6ccab972010-12-16 01:14:37 +000011450 // Check for unexpanded parameter packs.
11451 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11452 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11453 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11454 return 0;
11455
John McCall67d1a672009-08-06 02:15:43 +000011456 // The context we found the declaration in, or in which we should
11457 // create the declaration.
11458 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011459 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011460 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011461 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011462
Richard Smith4e9686b2013-08-09 04:35:01 +000011463 // There are five cases here.
11464 // - There's no scope specifier and we're in a local class. Only look
11465 // for functions declared in the immediately-enclosing block scope.
11466 // We recover from invalid scope qualifiers as if they just weren't there.
11467 FunctionDecl *FunctionContainingLocalClass = 0;
11468 if ((SS.isInvalid() || !SS.isSet()) &&
11469 (FunctionContainingLocalClass =
11470 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11471 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011472 // If a friend declaration appears in a local class and the name
11473 // specified is an unqualified name, a prior declaration is
11474 // looked up without considering scopes that are outside the
11475 // innermost enclosing non-class scope. For a friend function
11476 // declaration, if there is no prior declaration, the program is
11477 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011478
11479 // Find the innermost enclosing non-class scope. This is the block
11480 // scope containing the local class definition (or for a nested class,
11481 // the outer local class).
11482 DCScope = S->getFnParent();
11483
11484 // Look up the function name in the scope.
11485 Previous.clear(LookupLocalFriendName);
11486 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11487
11488 if (!Previous.empty()) {
11489 // All possible previous declarations must have the same context:
11490 // either they were declared at block scope or they are members of
11491 // one of the enclosing local classes.
11492 DC = Previous.getRepresentativeDecl()->getDeclContext();
11493 } else {
11494 // This is ill-formed, but provide the context that we would have
11495 // declared the function in, if we were permitted to, for error recovery.
11496 DC = FunctionContainingLocalClass;
11497 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011498 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011499
11500 // C++ [class.friend]p6:
11501 // A function can be defined in a friend declaration of a class if and
11502 // only if the class is a non-local class (9.8), the function name is
11503 // unqualified, and the function has namespace scope.
11504 if (D.isFunctionDefinition()) {
11505 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11506 }
11507
11508 // - There's no scope specifier, in which case we just go to the
11509 // appropriate scope and look for a function or function template
11510 // there as appropriate.
11511 } else if (SS.isInvalid() || !SS.isSet()) {
11512 // C++11 [namespace.memdef]p3:
11513 // If the name in a friend declaration is neither qualified nor
11514 // a template-id and the declaration is a function or an
11515 // elaborated-type-specifier, the lookup to determine whether
11516 // the entity has been previously declared shall not consider
11517 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011518 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011519
John McCall29ae6e52010-10-13 05:45:15 +000011520 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011521 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011522
Rafael Espindola11dc6342013-04-25 20:12:36 +000011523 // Skip class contexts. If someone can cite chapter and verse
11524 // for this behavior, that would be nice --- it's what GCC and
11525 // EDG do, and it seems like a reasonable intent, but the spec
11526 // really only says that checks for unqualified existing
11527 // declarations should stop at the nearest enclosing namespace,
11528 // not that they should only consider the nearest enclosing
11529 // namespace.
11530 while (DC->isRecord())
11531 DC = DC->getParent();
11532
11533 DeclContext *LookupDC = DC;
11534 while (LookupDC->isTransparentContext())
11535 LookupDC = LookupDC->getParent();
11536
11537 while (true) {
11538 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011539
Rafael Espindola11dc6342013-04-25 20:12:36 +000011540 if (!Previous.empty()) {
11541 DC = LookupDC;
11542 break;
John McCall8a407372010-10-14 22:22:28 +000011543 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011544
11545 if (isTemplateId) {
11546 if (isa<TranslationUnitDecl>(LookupDC)) break;
11547 } else {
11548 if (LookupDC->isFileContext()) break;
11549 }
11550 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011551 }
11552
John McCall380aaa42010-10-13 06:22:15 +000011553 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011554
John McCall337ec3d2010-10-12 23:13:28 +000011555 // - There's a non-dependent scope specifier, in which case we
11556 // compute it and do a previous lookup there for a function
11557 // or function template.
11558 } else if (!SS.getScopeRep()->isDependent()) {
11559 DC = computeDeclContext(SS);
11560 if (!DC) return 0;
11561
11562 if (RequireCompleteDeclContext(SS, DC)) return 0;
11563
11564 LookupQualifiedName(Previous, DC);
11565
11566 // Ignore things found implicitly in the wrong scope.
11567 // TODO: better diagnostics for this case. Suggesting the right
11568 // qualified scope would be nice...
11569 LookupResult::Filter F = Previous.makeFilter();
11570 while (F.hasNext()) {
11571 NamedDecl *D = F.next();
11572 if (!DC->InEnclosingNamespaceSetOf(
11573 D->getDeclContext()->getRedeclContext()))
11574 F.erase();
11575 }
11576 F.done();
11577
11578 if (Previous.empty()) {
11579 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011580 Diag(Loc, diag::err_qualified_friend_not_found)
11581 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011582 return 0;
11583 }
11584
11585 // C++ [class.friend]p1: A friend of a class is a function or
11586 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011587 if (DC->Equals(CurContext))
11588 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011589 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011590 diag::warn_cxx98_compat_friend_is_member :
11591 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011592
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011593 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011594 // C++ [class.friend]p6:
11595 // A function can be defined in a friend declaration of a class if and
11596 // only if the class is a non-local class (9.8), the function name is
11597 // unqualified, and the function has namespace scope.
11598 SemaDiagnosticBuilder DB
11599 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11600
11601 DB << SS.getScopeRep();
11602 if (DC->isFileContext())
11603 DB << FixItHint::CreateRemoval(SS.getRange());
11604 SS.clear();
11605 }
John McCall337ec3d2010-10-12 23:13:28 +000011606
11607 // - There's a scope specifier that does not match any template
11608 // parameter lists, in which case we use some arbitrary context,
11609 // create a method or method template, and wait for instantiation.
11610 // - There's a scope specifier that does match some template
11611 // parameter lists, which we don't handle right now.
11612 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011613 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011614 // C++ [class.friend]p6:
11615 // A function can be defined in a friend declaration of a class if and
11616 // only if the class is a non-local class (9.8), the function name is
11617 // unqualified, and the function has namespace scope.
11618 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11619 << SS.getScopeRep();
11620 }
11621
John McCall337ec3d2010-10-12 23:13:28 +000011622 DC = CurContext;
11623 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011624 }
Douglas Gregor883af832011-10-10 01:11:59 +000011625
John McCall29ae6e52010-10-13 05:45:15 +000011626 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011627 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011628 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11629 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11630 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011631 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011632 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11633 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011634 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011635 }
John McCall67d1a672009-08-06 02:15:43 +000011636 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011637
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011638 // FIXME: This is an egregious hack to cope with cases where the scope stack
11639 // does not contain the declaration context, i.e., in an out-of-line
11640 // definition of a class.
11641 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11642 if (!DCScope) {
11643 FakeDCScope.setEntity(DC);
11644 DCScope = &FakeDCScope;
11645 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011646
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011647 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011648 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011649 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011650 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011651
Douglas Gregor182ddf02009-09-28 00:08:27 +000011652 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011653
Richard Smith4e9686b2013-08-09 04:35:01 +000011654 // If we performed typo correction, we might have added a scope specifier
11655 // and changed the decl context.
11656 DC = ND->getDeclContext();
11657
John McCallab88d972009-08-31 22:39:49 +000011658 // Add the function declaration to the appropriate lookup tables,
11659 // adjusting the redeclarations list as necessary. We don't
11660 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011661 //
John McCallab88d972009-08-31 22:39:49 +000011662 // Also update the scope-based lookup if the target context's
11663 // lookup context is in lexical scope.
11664 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011665 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011666 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011667 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011668 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011669 }
John McCall02cace72009-08-28 07:59:38 +000011670
11671 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011672 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011673 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011674 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011675 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011676
John McCall1f2e1a92012-08-10 03:15:35 +000011677 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011678 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011679 } else {
11680 if (DC->isRecord()) CheckFriendAccess(ND);
11681
John McCall6102ca12010-10-16 06:59:13 +000011682 FunctionDecl *FD;
11683 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11684 FD = FTD->getTemplatedDecl();
11685 else
11686 FD = cast<FunctionDecl>(ND);
11687
David Majnemerf6a144f2013-06-25 23:09:30 +000011688 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11689 // default argument expression, that declaration shall be a definition
11690 // and shall be the only declaration of the function or function
11691 // template in the translation unit.
11692 if (functionDeclHasDefaultArgument(FD)) {
11693 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11694 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11695 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11696 } else if (!D.isFunctionDefinition())
11697 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11698 }
11699
John McCall6102ca12010-10-16 06:59:13 +000011700 // Mark templated-scope function declarations as unsupported.
11701 if (FD->getNumTemplateParameterLists())
11702 FrD->setUnsupportedFriend(true);
11703 }
John McCall337ec3d2010-10-12 23:13:28 +000011704
John McCalld226f652010-08-21 09:40:31 +000011705 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011706}
11707
John McCalld226f652010-08-21 09:40:31 +000011708void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11709 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011710
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011711 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011712 if (!Fn) {
11713 Diag(DelLoc, diag::err_deleted_non_function);
11714 return;
11715 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011716
Douglas Gregoref96ee02012-01-14 16:38:05 +000011717 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011718 // Don't consider the implicit declaration we generate for explicit
11719 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011720 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11721 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011722 Diag(DelLoc, diag::err_deleted_decl_not_first);
11723 Diag(Prev->getLocation(), diag::note_previous_declaration);
11724 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011725 // If the declaration wasn't the first, we delete the function anyway for
11726 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011727 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011728 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011729
11730 if (Fn->isDeleted())
11731 return;
11732
11733 // See if we're deleting a function which is already known to override a
11734 // non-deleted virtual function.
11735 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11736 bool IssuedDiagnostic = false;
11737 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11738 E = MD->end_overridden_methods();
11739 I != E; ++I) {
11740 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11741 if (!IssuedDiagnostic) {
11742 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11743 IssuedDiagnostic = true;
11744 }
11745 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11746 }
11747 }
11748 }
11749
Sean Hunt10620eb2011-05-06 20:44:56 +000011750 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011751}
Sebastian Redl13e88542009-04-27 21:33:24 +000011752
Sean Hunte4246a62011-05-12 06:15:49 +000011753void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011754 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011755
11756 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011757 if (MD->getParent()->isDependentType()) {
11758 MD->setDefaulted();
11759 MD->setExplicitlyDefaulted();
11760 return;
11761 }
11762
Sean Hunte4246a62011-05-12 06:15:49 +000011763 CXXSpecialMember Member = getSpecialMember(MD);
11764 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011765 if (!MD->isInvalidDecl())
11766 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011767 return;
11768 }
11769
11770 MD->setDefaulted();
11771 MD->setExplicitlyDefaulted();
11772
Sean Huntcd10dec2011-05-23 23:14:04 +000011773 // If this definition appears within the record, do the checking when
11774 // the record is complete.
11775 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011776 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011777 // Find the uninstantiated declaration that actually had the '= default'
11778 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011779 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011780
Richard Smith12fef492013-03-27 00:22:47 +000011781 // If the method was defaulted on its first declaration, we will have
11782 // already performed the checking in CheckCompletedCXXClass. Such a
11783 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011784 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011785 return;
11786
Richard Smithb9d0b762012-07-27 04:22:15 +000011787 CheckExplicitlyDefaultedSpecialMember(MD);
11788
Richard Smith1d28caf2012-12-11 01:14:52 +000011789 // The exception specification is needed because we are defining the
11790 // function.
11791 ResolveExceptionSpec(DefaultLoc,
11792 MD->getType()->castAs<FunctionProtoType>());
11793
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011794 if (MD->isInvalidDecl())
11795 return;
11796
Sean Hunte4246a62011-05-12 06:15:49 +000011797 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011798 case CXXDefaultConstructor:
11799 DefineImplicitDefaultConstructor(DefaultLoc,
11800 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011801 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011802 case CXXCopyConstructor:
11803 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011804 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011805 case CXXCopyAssignment:
11806 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011807 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011808 case CXXDestructor:
11809 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011810 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011811 case CXXMoveConstructor:
11812 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011813 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011814 case CXXMoveAssignment:
11815 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011816 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011817 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011818 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011819 }
11820 } else {
11821 Diag(DefaultLoc, diag::err_default_special_members);
11822 }
11823}
11824
Sebastian Redl13e88542009-04-27 21:33:24 +000011825static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011826 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011827 Stmt *SubStmt = *CI;
11828 if (!SubStmt)
11829 continue;
11830 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011831 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011832 diag::err_return_in_constructor_handler);
11833 if (!isa<Expr>(SubStmt))
11834 SearchForReturnInStmt(Self, SubStmt);
11835 }
11836}
11837
11838void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11839 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11840 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11841 SearchForReturnInStmt(*this, Handler);
11842 }
11843}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011844
David Blaikie299adab2013-01-18 23:03:15 +000011845bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011846 const CXXMethodDecl *Old) {
11847 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11848 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11849
11850 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11851
11852 // If the calling conventions match, everything is fine
11853 if (NewCC == OldCC)
11854 return false;
11855
Reid Kleckneref072032013-08-27 23:08:25 +000011856 Diag(New->getLocation(),
11857 diag::err_conflicting_overriding_cc_attributes)
11858 << New->getDeclName() << New->getType() << Old->getType();
11859 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11860 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011861}
11862
Mike Stump1eb44332009-09-09 15:08:12 +000011863bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011864 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011865 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11866 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011867
Chandler Carruth73857792010-02-15 11:53:20 +000011868 if (Context.hasSameType(NewTy, OldTy) ||
11869 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011870 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011871
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011872 // Check if the return types are covariant
11873 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011874
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011875 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011876 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11877 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011878 NewClassTy = NewPT->getPointeeType();
11879 OldClassTy = OldPT->getPointeeType();
11880 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011881 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11882 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11883 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11884 NewClassTy = NewRT->getPointeeType();
11885 OldClassTy = OldRT->getPointeeType();
11886 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011887 }
11888 }
Mike Stump1eb44332009-09-09 15:08:12 +000011889
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011890 // The return types aren't either both pointers or references to a class type.
11891 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011892 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011893 diag::err_different_return_type_for_overriding_virtual_function)
11894 << New->getDeclName() << NewTy << OldTy;
11895 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011896
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011897 return true;
11898 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011899
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011900 // C++ [class.virtual]p6:
11901 // If the return type of D::f differs from the return type of B::f, the
11902 // class type in the return type of D::f shall be complete at the point of
11903 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011904 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11905 if (!RT->isBeingDefined() &&
11906 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011907 diag::err_covariant_return_incomplete,
11908 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011909 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011910 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011911
Douglas Gregora4923eb2009-11-16 21:35:15 +000011912 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011913 // Check if the new class derives from the old class.
11914 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11915 Diag(New->getLocation(),
11916 diag::err_covariant_return_not_derived)
11917 << New->getDeclName() << NewTy << OldTy;
11918 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11919 return true;
11920 }
Mike Stump1eb44332009-09-09 15:08:12 +000011921
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011922 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011923 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011924 diag::err_covariant_return_inaccessible_base,
11925 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11926 // FIXME: Should this point to the return type?
11927 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011928 // FIXME: this note won't trigger for delayed access control
11929 // diagnostics, and it's impossible to get an undelayed error
11930 // here from access control during the original parse because
11931 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011932 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11933 return true;
11934 }
11935 }
Mike Stump1eb44332009-09-09 15:08:12 +000011936
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011937 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011938 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011939 Diag(New->getLocation(),
11940 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011941 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011942 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11943 return true;
11944 };
Mike Stump1eb44332009-09-09 15:08:12 +000011945
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011946
11947 // The new class type must have the same or less qualifiers as the old type.
11948 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11949 Diag(New->getLocation(),
11950 diag::err_covariant_return_type_class_type_more_qualified)
11951 << New->getDeclName() << NewTy << OldTy;
11952 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11953 return true;
11954 };
Mike Stump1eb44332009-09-09 15:08:12 +000011955
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011956 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011957}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011958
Douglas Gregor4ba31362009-12-01 17:24:26 +000011959/// \brief Mark the given method pure.
11960///
11961/// \param Method the method to be marked pure.
11962///
11963/// \param InitRange the source range that covers the "0" initializer.
11964bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011965 SourceLocation EndLoc = InitRange.getEnd();
11966 if (EndLoc.isValid())
11967 Method->setRangeEnd(EndLoc);
11968
Douglas Gregor4ba31362009-12-01 17:24:26 +000011969 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11970 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011971 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011972 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011973
11974 if (!Method->isInvalidDecl())
11975 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11976 << Method->getDeclName() << InitRange;
11977 return true;
11978}
11979
Douglas Gregor552e2992012-02-21 02:22:07 +000011980/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011981static bool isStaticDataMember(const Decl *D) {
11982 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
11983 return Var->isStaticDataMember();
11984
11985 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000011986}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011987
John McCall731ad842009-12-19 09:28:58 +000011988/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11989/// an initializer for the out-of-line declaration 'Dcl'. The scope
11990/// is a fresh scope pushed for just this purpose.
11991///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011992/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11993/// static data member of class X, names should be looked up in the scope of
11994/// class X.
John McCalld226f652010-08-21 09:40:31 +000011995void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011996 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011997 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011998
John McCall731ad842009-12-19 09:28:58 +000011999 // We should only get called for declarations with scope specifiers, like:
12000 // int foo::bar;
12001 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012002 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000012003
12004 // If we are parsing the initializer for a static data member, push a
12005 // new expression evaluation context that is associated with this static
12006 // data member.
12007 if (isStaticDataMember(D))
12008 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012009}
12010
12011/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012012/// initializer for the out-of-line declaration 'D'.
12013void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012014 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012015 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012016
Douglas Gregor552e2992012-02-21 02:22:07 +000012017 if (isStaticDataMember(D))
12018 PopExpressionEvaluationContext();
12019
John McCall731ad842009-12-19 09:28:58 +000012020 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012021 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012022}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012023
12024/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12025/// C++ if/switch/while/for statement.
12026/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012027DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012028 // C++ 6.4p2:
12029 // The declarator shall not specify a function or an array.
12030 // The type-specifier-seq shall not contain typedef and shall not declare a
12031 // new class or enumeration.
12032 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12033 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012034
12035 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012036 if (!Dcl)
12037 return true;
12038
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012039 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12040 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012041 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012042 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012043 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012044
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012045 return Dcl;
12046}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012047
Douglas Gregordfe65432011-07-28 19:11:31 +000012048void Sema::LoadExternalVTableUses() {
12049 if (!ExternalSource)
12050 return;
12051
12052 SmallVector<ExternalVTableUse, 4> VTables;
12053 ExternalSource->ReadUsedVTables(VTables);
12054 SmallVector<VTableUse, 4> NewUses;
12055 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12056 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12057 = VTablesUsed.find(VTables[I].Record);
12058 // Even if a definition wasn't required before, it may be required now.
12059 if (Pos != VTablesUsed.end()) {
12060 if (!Pos->second && VTables[I].DefinitionRequired)
12061 Pos->second = true;
12062 continue;
12063 }
12064
12065 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12066 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12067 }
12068
12069 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12070}
12071
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012072void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12073 bool DefinitionRequired) {
12074 // Ignore any vtable uses in unevaluated operands or for classes that do
12075 // not have a vtable.
12076 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012077 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012078 return;
12079
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012080 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012081 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012082 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12083 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12084 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12085 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012086 // If we already had an entry, check to see if we are promoting this vtable
12087 // to required a definition. If so, we need to reappend to the VTableUses
12088 // list, since we may have already processed the first entry.
12089 if (DefinitionRequired && !Pos.first->second) {
12090 Pos.first->second = true;
12091 } else {
12092 // Otherwise, we can early exit.
12093 return;
12094 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012095 }
12096
12097 // Local classes need to have their virtual members marked
12098 // immediately. For all other classes, we mark their virtual members
12099 // at the end of the translation unit.
12100 if (Class->isLocalClass())
12101 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012102 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012103 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012104}
12105
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012106bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012107 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012108 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012109 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012110
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012111 // Note: The VTableUses vector could grow as a result of marking
12112 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012113 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012114 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012115 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012116 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012117 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012118 if (!Class)
12119 continue;
12120
12121 SourceLocation Loc = VTableUses[I].second;
12122
Richard Smithb9d0b762012-07-27 04:22:15 +000012123 bool DefineVTable = true;
12124
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012125 // If this class has a key function, but that key function is
12126 // defined in another translation unit, we don't need to emit the
12127 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012128 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012129 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012130 // The key function is in another translation unit.
12131 DefineVTable = false;
12132 TemplateSpecializationKind TSK =
12133 KeyFunction->getTemplateSpecializationKind();
12134 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12135 TSK != TSK_ImplicitInstantiation &&
12136 "Instantiations don't have key functions");
12137 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012138 } else if (!KeyFunction) {
12139 // If we have a class with no key function that is the subject
12140 // of an explicit instantiation declaration, suppress the
12141 // vtable; it will live with the explicit instantiation
12142 // definition.
12143 bool IsExplicitInstantiationDeclaration
12144 = Class->getTemplateSpecializationKind()
12145 == TSK_ExplicitInstantiationDeclaration;
12146 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12147 REnd = Class->redecls_end();
12148 R != REnd; ++R) {
12149 TemplateSpecializationKind TSK
12150 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12151 if (TSK == TSK_ExplicitInstantiationDeclaration)
12152 IsExplicitInstantiationDeclaration = true;
12153 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12154 IsExplicitInstantiationDeclaration = false;
12155 break;
12156 }
12157 }
12158
12159 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012160 DefineVTable = false;
12161 }
12162
12163 // The exception specifications for all virtual members may be needed even
12164 // if we are not providing an authoritative form of the vtable in this TU.
12165 // We may choose to emit it available_externally anyway.
12166 if (!DefineVTable) {
12167 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12168 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012169 }
12170
12171 // Mark all of the virtual members of this class as referenced, so
12172 // that we can build a vtable. Then, tell the AST consumer that a
12173 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012174 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012175 MarkVirtualMembersReferenced(Loc, Class);
12176 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12177 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12178
12179 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012180 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012181 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012182 const FunctionDecl *KeyFunctionDef = 0;
12183 if (!KeyFunction ||
12184 (KeyFunction->hasBody(KeyFunctionDef) &&
12185 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012186 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12187 TSK_ExplicitInstantiationDefinition
12188 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12189 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012190 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012191 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012192 VTableUses.clear();
12193
Douglas Gregor78844032011-04-22 22:25:37 +000012194 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012195}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012196
Richard Smithb9d0b762012-07-27 04:22:15 +000012197void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12198 const CXXRecordDecl *RD) {
12199 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12200 E = RD->method_end(); I != E; ++I)
12201 if ((*I)->isVirtual() && !(*I)->isPure())
12202 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12203}
12204
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012205void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12206 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012207 // Mark all functions which will appear in RD's vtable as used.
12208 CXXFinalOverriderMap FinalOverriders;
12209 RD->getFinalOverriders(FinalOverriders);
12210 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12211 E = FinalOverriders.end();
12212 I != E; ++I) {
12213 for (OverridingMethods::const_iterator OI = I->second.begin(),
12214 OE = I->second.end();
12215 OI != OE; ++OI) {
12216 assert(OI->second.size() > 0 && "no final overrider");
12217 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012218
Richard Smithff817f72012-07-07 06:59:51 +000012219 // C++ [basic.def.odr]p2:
12220 // [...] A virtual member function is used if it is not pure. [...]
12221 if (!Overrider->isPure())
12222 MarkFunctionReferenced(Loc, Overrider);
12223 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012224 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012225
12226 // Only classes that have virtual bases need a VTT.
12227 if (RD->getNumVBases() == 0)
12228 return;
12229
12230 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12231 e = RD->bases_end(); i != e; ++i) {
12232 const CXXRecordDecl *Base =
12233 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012234 if (Base->getNumVBases() == 0)
12235 continue;
12236 MarkVirtualMembersReferenced(Loc, Base);
12237 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012238}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012239
12240/// SetIvarInitializers - This routine builds initialization ASTs for the
12241/// Objective-C implementation whose ivars need be initialized.
12242void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012243 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012244 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012245 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012246 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012247 CollectIvarsToConstructOrDestruct(OID, ivars);
12248 if (ivars.empty())
12249 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012250 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012251 for (unsigned i = 0; i < ivars.size(); i++) {
12252 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012253 if (Field->isInvalidDecl())
12254 continue;
12255
Sean Huntcbb67482011-01-08 20:30:50 +000012256 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012257 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12258 InitializationKind InitKind =
12259 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012260
12261 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12262 ExprResult MemberInit =
12263 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012264 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012265 // Note, MemberInit could actually come back empty if no initialization
12266 // is required (e.g., because it would call a trivial default constructor)
12267 if (!MemberInit.get() || MemberInit.isInvalid())
12268 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012269
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012270 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012271 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12272 SourceLocation(),
12273 MemberInit.takeAs<Expr>(),
12274 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012275 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012276
12277 // Be sure that the destructor is accessible and is marked as referenced.
12278 if (const RecordType *RecordTy
12279 = Context.getBaseElementType(Field->getType())
12280 ->getAs<RecordType>()) {
12281 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012282 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012283 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012284 CheckDestructorAccess(Field->getLocation(), Destructor,
12285 PDiag(diag::err_access_dtor_ivar)
12286 << Context.getBaseElementType(Field->getType()));
12287 }
12288 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012289 }
12290 ObjCImplementation->setIvarInitializers(Context,
12291 AllToInit.data(), AllToInit.size());
12292 }
12293}
Sean Huntfe57eef2011-05-04 05:57:24 +000012294
Sean Huntebcbe1d2011-05-04 23:29:54 +000012295static
12296void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12297 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12298 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12299 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12300 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012301 if (Ctor->isInvalidDecl())
12302 return;
12303
Richard Smitha8eaf002012-08-23 06:16:52 +000012304 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12305
12306 // Target may not be determinable yet, for instance if this is a dependent
12307 // call in an uninstantiated template.
12308 if (Target) {
12309 const FunctionDecl *FNTarget = 0;
12310 (void)Target->hasBody(FNTarget);
12311 Target = const_cast<CXXConstructorDecl*>(
12312 cast_or_null<CXXConstructorDecl>(FNTarget));
12313 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012314
12315 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12316 // Avoid dereferencing a null pointer here.
12317 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12318
12319 if (!Current.insert(Canonical))
12320 return;
12321
12322 // We know that beyond here, we aren't chaining into a cycle.
12323 if (!Target || !Target->isDelegatingConstructor() ||
12324 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012325 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012326 Current.clear();
12327 // We've hit a cycle.
12328 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12329 Current.count(TCanonical)) {
12330 // If we haven't diagnosed this cycle yet, do so now.
12331 if (!Invalid.count(TCanonical)) {
12332 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012333 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012334 << Ctor;
12335
Richard Smitha8eaf002012-08-23 06:16:52 +000012336 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012337 if (TCanonical != Canonical)
12338 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12339
12340 CXXConstructorDecl *C = Target;
12341 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012342 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012343 (void)C->getTargetConstructor()->hasBody(FNTarget);
12344 assert(FNTarget && "Ctor cycle through bodiless function");
12345
Richard Smitha8eaf002012-08-23 06:16:52 +000012346 C = const_cast<CXXConstructorDecl*>(
12347 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012348 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12349 }
12350 }
12351
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012352 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012353 Current.clear();
12354 } else {
12355 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12356 }
12357}
12358
12359
Sean Huntfe57eef2011-05-04 05:57:24 +000012360void Sema::CheckDelegatingCtorCycles() {
12361 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12362
Douglas Gregor0129b562011-07-27 21:57:17 +000012363 for (DelegatingCtorDeclsType::iterator
12364 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012365 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012366 I != E; ++I)
12367 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012368
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012369 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12370 CE = Invalid.end();
12371 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012372 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012373}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012374
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012375namespace {
12376 /// \brief AST visitor that finds references to the 'this' expression.
12377 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12378 Sema &S;
12379
12380 public:
12381 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12382
12383 bool VisitCXXThisExpr(CXXThisExpr *E) {
12384 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12385 << E->isImplicit();
12386 return false;
12387 }
12388 };
12389}
12390
12391bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12392 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12393 if (!TSInfo)
12394 return false;
12395
12396 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012397 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012398 if (!ProtoTL)
12399 return false;
12400
12401 // C++11 [expr.prim.general]p3:
12402 // [The expression this] shall not appear before the optional
12403 // cv-qualifier-seq and it shall not appear within the declaration of a
12404 // static member function (although its type and value category are defined
12405 // within a static member function as they are within a non-static member
12406 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012407 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012408 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012409 FindCXXThisExpr Finder(*this);
12410
12411 // If the return type came after the cv-qualifier-seq, check it now.
12412 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012413 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012414 return true;
12415
12416 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012417 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12418 return true;
12419
12420 return checkThisInStaticMemberFunctionAttributes(Method);
12421}
12422
12423bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12424 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12425 if (!TSInfo)
12426 return false;
12427
12428 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012429 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012430 if (!ProtoTL)
12431 return false;
12432
David Blaikie39e6ab42013-02-18 22:06:02 +000012433 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012434 FindCXXThisExpr Finder(*this);
12435
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012436 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012437 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012438 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012439 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012440 case EST_DynamicNone:
12441 case EST_MSAny:
12442 case EST_None:
12443 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012444
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012445 case EST_ComputedNoexcept:
12446 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12447 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012448
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012449 case EST_Dynamic:
12450 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012451 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012452 E != EEnd; ++E) {
12453 if (!Finder.TraverseType(*E))
12454 return true;
12455 }
12456 break;
12457 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012458
12459 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012460}
12461
12462bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12463 FindCXXThisExpr Finder(*this);
12464
12465 // Check attributes.
12466 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12467 A != AEnd; ++A) {
12468 // FIXME: This should be emitted by tblgen.
12469 Expr *Arg = 0;
12470 ArrayRef<Expr *> Args;
12471 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12472 Arg = G->getArg();
12473 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12474 Arg = G->getArg();
12475 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12476 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12477 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12478 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12479 else if (ExclusiveLockFunctionAttr *ELF
12480 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12481 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12482 else if (SharedLockFunctionAttr *SLF
12483 = dyn_cast<SharedLockFunctionAttr>(*A))
12484 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12485 else if (ExclusiveTrylockFunctionAttr *ETLF
12486 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12487 Arg = ETLF->getSuccessValue();
12488 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12489 } else if (SharedTrylockFunctionAttr *STLF
12490 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12491 Arg = STLF->getSuccessValue();
12492 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12493 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12494 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12495 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12496 Arg = LR->getArg();
12497 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12498 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12499 else if (ExclusiveLocksRequiredAttr *ELR
12500 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12501 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12502 else if (SharedLocksRequiredAttr *SLR
12503 = dyn_cast<SharedLocksRequiredAttr>(*A))
12504 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12505
12506 if (Arg && !Finder.TraverseStmt(Arg))
12507 return true;
12508
12509 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12510 if (!Finder.TraverseStmt(Args[I]))
12511 return true;
12512 }
12513 }
12514
12515 return false;
12516}
12517
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012518void
12519Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12520 ArrayRef<ParsedType> DynamicExceptions,
12521 ArrayRef<SourceRange> DynamicExceptionRanges,
12522 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012523 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012524 FunctionProtoType::ExtProtoInfo &EPI) {
12525 Exceptions.clear();
12526 EPI.ExceptionSpecType = EST;
12527 if (EST == EST_Dynamic) {
12528 Exceptions.reserve(DynamicExceptions.size());
12529 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12530 // FIXME: Preserve type source info.
12531 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12532
12533 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12534 collectUnexpandedParameterPacks(ET, Unexpanded);
12535 if (!Unexpanded.empty()) {
12536 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12537 UPPC_ExceptionType,
12538 Unexpanded);
12539 continue;
12540 }
12541
12542 // Check that the type is valid for an exception spec, and
12543 // drop it if not.
12544 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12545 Exceptions.push_back(ET);
12546 }
12547 EPI.NumExceptions = Exceptions.size();
12548 EPI.Exceptions = Exceptions.data();
12549 return;
12550 }
12551
12552 if (EST == EST_ComputedNoexcept) {
12553 // If an error occurred, there's no expression here.
12554 if (NoexceptExpr) {
12555 assert((NoexceptExpr->isTypeDependent() ||
12556 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12557 Context.BoolTy) &&
12558 "Parser should have made sure that the expression is boolean");
12559 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12560 EPI.ExceptionSpecType = EST_BasicNoexcept;
12561 return;
12562 }
12563
12564 if (!NoexceptExpr->isValueDependent())
12565 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012566 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012567 /*AllowFold*/ false).take();
12568 EPI.NoexceptExpr = NoexceptExpr;
12569 }
12570 return;
12571 }
12572}
12573
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012574/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12575Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12576 // Implicitly declared functions (e.g. copy constructors) are
12577 // __host__ __device__
12578 if (D->isImplicit())
12579 return CFT_HostDevice;
12580
12581 if (D->hasAttr<CUDAGlobalAttr>())
12582 return CFT_Global;
12583
12584 if (D->hasAttr<CUDADeviceAttr>()) {
12585 if (D->hasAttr<CUDAHostAttr>())
12586 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012587 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012588 }
12589
12590 return CFT_Host;
12591}
12592
12593bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12594 CUDAFunctionTarget CalleeTarget) {
12595 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12596 // Callable from the device only."
12597 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12598 return true;
12599
12600 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12601 // Callable from the host only."
12602 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12603 // Callable from the host only."
12604 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12605 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12606 return true;
12607
12608 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12609 return true;
12610
12611 return false;
12612}
John McCall76da55d2013-04-16 07:28:30 +000012613
12614/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12615///
12616MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12617 SourceLocation DeclStart,
12618 Declarator &D, Expr *BitWidth,
12619 InClassInitStyle InitStyle,
12620 AccessSpecifier AS,
12621 AttributeList *MSPropertyAttr) {
12622 IdentifierInfo *II = D.getIdentifier();
12623 if (!II) {
12624 Diag(DeclStart, diag::err_anonymous_property);
12625 return NULL;
12626 }
12627 SourceLocation Loc = D.getIdentifierLoc();
12628
12629 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12630 QualType T = TInfo->getType();
12631 if (getLangOpts().CPlusPlus) {
12632 CheckExtraCXXDefaultArguments(D);
12633
12634 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12635 UPPC_DataMemberType)) {
12636 D.setInvalidType();
12637 T = Context.IntTy;
12638 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12639 }
12640 }
12641
12642 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12643
12644 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12645 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12646 diag::err_invalid_thread)
12647 << DeclSpec::getSpecifierName(TSCS);
12648
12649 // Check to see if this name was declared as a member previously
12650 NamedDecl *PrevDecl = 0;
12651 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12652 LookupName(Previous, S);
12653 switch (Previous.getResultKind()) {
12654 case LookupResult::Found:
12655 case LookupResult::FoundUnresolvedValue:
12656 PrevDecl = Previous.getAsSingle<NamedDecl>();
12657 break;
12658
12659 case LookupResult::FoundOverloaded:
12660 PrevDecl = Previous.getRepresentativeDecl();
12661 break;
12662
12663 case LookupResult::NotFound:
12664 case LookupResult::NotFoundInCurrentInstantiation:
12665 case LookupResult::Ambiguous:
12666 break;
12667 }
12668
12669 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12670 // Maybe we will complain about the shadowed template parameter.
12671 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12672 // Just pretend that we didn't see the previous declaration.
12673 PrevDecl = 0;
12674 }
12675
12676 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12677 PrevDecl = 0;
12678
12679 SourceLocation TSSL = D.getLocStart();
12680 MSPropertyDecl *NewPD;
12681 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12682 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12683 II, T, TInfo, TSSL,
12684 Data.GetterId, Data.SetterId);
12685 ProcessDeclAttributes(TUScope, NewPD, D);
12686 NewPD->setAccess(AS);
12687
12688 if (NewPD->isInvalidDecl())
12689 Record->setInvalidDecl();
12690
12691 if (D.getDeclSpec().isModulePrivateSpecified())
12692 NewPD->setModulePrivate();
12693
12694 if (NewPD->isInvalidDecl() && PrevDecl) {
12695 // Don't introduce NewFD into scope; there's already something
12696 // with the same name in the same scope.
12697 } else if (II) {
12698 PushOnScopeChains(NewPD, S);
12699 } else
12700 Record->addDecl(NewPD);
12701
12702 return NewPD;
12703}