blob: 85394bb4de75d265e84493d8ed75afc5e40a87a0 [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-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 Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000041#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000042#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner58258242008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000060
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 public:
Mike Stump11289f42009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 };
Chris Lattner58258242008-04-10 02:22:51 +000071
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000078 }
79
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Dunbar62ee6412012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105 }
Chris Lattner58258242008-04-10 02:22:51 +0000106
Douglas Gregor8e12c382008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000109
Douglas Gregor97a9c812008-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 Dunbar62ee6412012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000118 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000119
John McCall7353c862013-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 Gregorf0d49512012-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 Lattner58258242008-04-10 02:22:51 +0000147}
148
Richard Smithb7151b92013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Alexis Hunt6d5b96c2011-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 Smithd3b5c9082012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith938f40b2011-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
Alexis Hunt6d5b96c2011-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 Smithf623c962012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-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.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
Anders Carlssonf1c26952009-08-25 01:02:06 +0000320 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000323 Param->setInvalidDecl();
324 return;
325 }
Mike Stump11289f42009-09-09 15:08:12 +0000326
John McCallb268a282010-08-23 23:25:46 +0000327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000328}
329
Douglas Gregor58354032008-12-24 00:01:03 +0000330/// ActOnParamUnparsedDefaultArgument - We've seen a default
331/// argument for a function parameter, but we can't parse it yet
332/// because we're inside a class definition. Note that this default
333/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000334void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000335 SourceLocation EqualLoc,
336 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000337 if (!param)
338 return;
Mike Stump11289f42009-09-09 15:08:12 +0000339
John McCall48871652010-08-21 09:40:31 +0000340 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000341 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000342 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000343}
344
Douglas Gregor4d87df52008-12-16 21:30:33 +0000345/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000347void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000348 if (!param)
349 return;
Mike Stump11289f42009-09-09 15:08:12 +0000350
John McCall48871652010-08-21 09:40:31 +0000351 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000352 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000354}
355
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000356/// CheckExtraCXXDefaultArguments - Check for any extra default
357/// arguments in the declarator, which is not a function declaration
358/// or definition and therefore is not permitted to have default
359/// arguments. This routine should be invoked for every declarator
360/// that is not a function declaration or definition.
361void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
362 // C++ [dcl.fct.default]p3
363 // A default argument expression shall be specified only in the
364 // parameter-declaration-clause of a function declaration or in a
365 // template-parameter (14.1). It shall not be specified for a
366 // parameter pack. If it is specified in a
367 // parameter-declaration-clause, it shall not occur within a
368 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000369 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000370 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000371 DeclaratorChunk &chunk = D.getTypeObject(i);
372 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000373 if (MightBeFunction) {
374 // This is a function declaration. It can have default arguments, but
375 // keep looking in case its return type is a function type with default
376 // arguments.
377 MightBeFunction = false;
378 continue;
379 }
Alp Tokerc5350722014-02-26 22:27:52 +0000380 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
381 ++argIdx) {
382 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000383 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000384 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000385 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000386 << SourceRange((*Toks)[1].getLocation(),
387 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000389 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000390 } else if (Param->getDefaultArg()) {
391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
392 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000393 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000394 }
395 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000396 } else if (chunk.Kind != DeclaratorChunk::Paren) {
397 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000398 }
399 }
400}
401
David Majnemer502b0ed2013-06-25 23:09:30 +0000402static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
403 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
404 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
405 if (!PVD->hasDefaultArg())
406 return false;
407 if (!PVD->hasInheritedDefaultArg())
408 return true;
409 }
410 return false;
411}
412
Craig Toppere4794282012-09-21 04:33:26 +0000413/// MergeCXXFunctionDecl - Merge two declarations of the same C++
414/// function, once we already know that they have the same
415/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
416/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000417bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
418 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000419 bool Invalid = false;
420
Chris Lattner199abbc2008-04-08 05:04:30 +0000421 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000422 // For non-template functions, default arguments can be added in
423 // later declarations of a function in the same
424 // scope. Declarations in different scopes have completely
425 // distinct sets of default arguments. That is, declarations in
426 // inner scopes do not acquire default arguments from
427 // declarations in outer scopes, and vice versa. In a given
428 // function declaration, all parameters subsequent to a
429 // parameter with a default argument shall have default
430 // arguments supplied in this or previous declarations. A
431 // default argument shall not be redefined by a later
432 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000433 //
434 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000435 // Except for member functions of class templates, the default arguments
436 // in a member function definition that appears outside of the class
437 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000438 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000439 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
440 ParmVarDecl *OldParam = Old->getParamDecl(p);
441 ParmVarDecl *NewParam = New->getParamDecl(p);
442
James Molloye9430032012-03-13 08:55:35 +0000443 bool OldParamHasDfl = OldParam->hasDefaultArg();
444 bool NewParamHasDfl = NewParam->hasDefaultArg();
445
446 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000447
448 // The declaration context corresponding to the scope is the semantic
449 // parent, unless this is a local function declaration, in which case
450 // it is that surrounding function.
451 DeclContext *ScopeDC = New->getLexicalDeclContext();
452 if (!ScopeDC->isFunctionOrMethod())
453 ScopeDC = New->getDeclContext();
454 if (S && !isDeclInScope(ND, ScopeDC, S) &&
455 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000456 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000457 // the same scope and this is not an out-of-line definition of
458 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000459 OldParamHasDfl = false;
460
461 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000462
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000463 unsigned DiagDefaultParamID =
464 diag::err_param_default_argument_redefinition;
465
466 // MSVC accepts that default parameters be redefined for member functions
467 // of template class. The new default parameter's value is ignored.
468 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000469 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000470 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
471 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000472 // Merge the old default argument into the new parameter.
473 NewParam->setHasInheritedDefaultArg();
474 if (OldParam->hasUninstantiatedDefaultArg())
475 NewParam->setUninstantiatedDefaultArg(
476 OldParam->getUninstantiatedDefaultArg());
477 else
478 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000479 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000480 Invalid = false;
481 }
482 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000483
Francois Pichet8cb243a2011-04-10 04:58:30 +0000484 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
485 // hint here. Alternatively, we could walk the type-source information
486 // for NewParam to find the last source location in the type... but it
487 // isn't worth the effort right now. This is the kind of test case that
488 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000489 // int f(int);
490 // void g(int (*fp)(int) = f);
491 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000492 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000493 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000494
495 // Look for the function declaration where the default argument was
496 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000497 for (FunctionDecl *Older = Old->getPreviousDecl();
498 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000499 if (!Older->getParamDecl(p)->hasDefaultArg())
500 break;
501
502 OldParam = Older->getParamDecl(p);
503 }
504
505 Diag(OldParam->getLocation(), diag::note_previous_definition)
506 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000507 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000508 // Merge the old default argument into the new parameter.
509 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000510 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000511 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000512 if (OldParam->hasUninstantiatedDefaultArg())
513 NewParam->setUninstantiatedDefaultArg(
514 OldParam->getUninstantiatedDefaultArg());
515 else
John McCalle61b02b2010-05-04 01:53:42 +0000516 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000517 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000518 if (New->getDescribedFunctionTemplate()) {
519 // Paragraph 4, quoted above, only applies to non-template functions.
520 Diag(NewParam->getLocation(),
521 diag::err_param_default_argument_template_redecl)
522 << NewParam->getDefaultArgRange();
523 Diag(Old->getLocation(), diag::note_template_prev_declaration)
524 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000525 } else if (New->getTemplateSpecializationKind()
526 != TSK_ImplicitInstantiation &&
527 New->getTemplateSpecializationKind() != TSK_Undeclared) {
528 // C++ [temp.expr.spec]p21:
529 // Default function arguments shall not be specified in a declaration
530 // or a definition for one of the following explicit specializations:
531 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000532 // - the explicit specialization of a member function template;
533 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000534 // template where the class template specialization to which the
535 // member function specialization belongs is implicitly
536 // instantiated.
537 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
538 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
539 << New->getDeclName()
540 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000541 } else if (New->getDeclContext()->isDependentContext()) {
542 // C++ [dcl.fct.default]p6 (DR217):
543 // Default arguments for a member function of a class template shall
544 // be specified on the initial declaration of the member function
545 // within the class template.
546 //
547 // Reading the tea leaves a bit in DR217 and its reference to DR205
548 // leads me to the conclusion that one cannot add default function
549 // arguments for an out-of-line definition of a member function of a
550 // dependent type.
551 int WhichKind = 2;
552 if (CXXRecordDecl *Record
553 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
554 if (Record->getDescribedClassTemplate())
555 WhichKind = 0;
556 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
557 WhichKind = 1;
558 else
559 WhichKind = 2;
560 }
561
562 Diag(NewParam->getLocation(),
563 diag::err_param_default_argument_member_template_redecl)
564 << WhichKind
565 << NewParam->getDefaultArgRange();
566 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000567 }
568 }
569
Richard Smith58c3cc12012-11-28 03:45:24 +0000570 // DR1344: If a default argument is added outside a class definition and that
571 // default argument makes the function a special member function, the program
572 // is ill-formed. This can only happen for constructors.
573 if (isa<CXXConstructorDecl>(New) &&
574 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
575 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
576 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
577 if (NewSM != OldSM) {
578 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
579 assert(NewParam->hasDefaultArg());
580 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
581 << NewParam->getDefaultArgRange() << NewSM;
582 Diag(Old->getLocation(), diag::note_previous_declaration);
583 }
584 }
585
David Majnemeree4f4022014-03-30 06:44:54 +0000586 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000587 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000588 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000589 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000590 if (New->isConstexpr() != Old->isConstexpr()) {
591 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
592 << New << New->isConstexpr();
593 Diag(Old->getLocation(), diag::note_previous_declaration);
594 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000595 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
596 // C++11 [dcl.fcn.spec]p4:
597 // If the definition of a function appears in a translation unit before its
598 // first declaration as inline, the program is ill-formed.
599 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
600 Diag(Def->getLocation(), diag::note_previous_definition);
601 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000602 }
603
David Majnemer502b0ed2013-06-25 23:09:30 +0000604 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000605 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000606 // the only declaration of the function or function template in the
607 // translation unit.
608 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
609 functionDeclHasDefaultArgument(Old)) {
610 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
611 Diag(Old->getLocation(), diag::note_previous_declaration);
612 Invalid = true;
613 }
614
Douglas Gregorf40863c2010-02-12 07:32:17 +0000615 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000616 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000617
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000618 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000619}
620
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000621/// \brief Merge the exception specifications of two variable declarations.
622///
623/// This is called when there's a redeclaration of a VarDecl. The function
624/// checks if the redeclaration might have an exception specification and
625/// validates compatibility and merges the specs if necessary.
626void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
627 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000628 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000629 return;
630
631 assert(Context.hasSameType(New->getType(), Old->getType()) &&
632 "Should only be called if types are otherwise the same.");
633
634 QualType NewType = New->getType();
635 QualType OldType = Old->getType();
636
637 // We're only interested in pointers and references to functions, as well
638 // as pointers to member functions.
639 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
640 NewType = R->getPointeeType();
641 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
642 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
643 NewType = P->getPointeeType();
644 OldType = OldType->getAs<PointerType>()->getPointeeType();
645 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
646 NewType = M->getPointeeType();
647 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
648 }
649
650 if (!NewType->isFunctionProtoType())
651 return;
652
653 // There's lots of special cases for functions. For function pointers, system
654 // libraries are hopefully not as broken so that we don't need these
655 // workarounds.
656 if (CheckEquivalentExceptionSpec(
657 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
658 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
659 New->setInvalidDecl();
660 }
661}
662
Chris Lattner199abbc2008-04-08 05:04:30 +0000663/// CheckCXXDefaultArguments - Verify that the default arguments for a
664/// function declaration are well-formed according to C++
665/// [dcl.fct.default].
666void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
667 unsigned NumParams = FD->getNumParams();
668 unsigned p;
669
670 // Find first parameter with a default argument
671 for (p = 0; p < NumParams; ++p) {
672 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000673 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000674 break;
675 }
676
677 // C++ [dcl.fct.default]p4:
678 // In a given function declaration, all parameters
679 // subsequent to a parameter with a default argument shall
680 // have default arguments supplied in this or previous
681 // declarations. A default argument shall not be redefined
682 // by a later declaration (not even to the same value).
683 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000684 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000685 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000686 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000687 if (Param->isInvalidDecl())
688 /* We already complained about this parameter. */;
689 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000690 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000691 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000692 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000693 else
Mike Stump11289f42009-09-09 15:08:12 +0000694 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000695 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattner199abbc2008-04-08 05:04:30 +0000697 LastMissingDefaultArg = p;
698 }
699 }
700
701 if (LastMissingDefaultArg > 0) {
702 // Some default arguments were missing. Clear out all of the
703 // default arguments up to (and including) the last missing
704 // default argument, so that we leave the function parameters
705 // in a semantically valid state.
706 for (p = 0; p <= LastMissingDefaultArg; ++p) {
707 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000708 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000709 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 }
711 }
712 }
713}
Douglas Gregor556877c2008-04-13 21:30:24 +0000714
Richard Smitheb3c10c2011-10-01 02:31:28 +0000715// CheckConstexprParameterTypes - Check whether a function's parameter types
716// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000717// diagnostic and return false.
718static bool CheckConstexprParameterTypes(Sema &SemaRef,
719 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000720 unsigned ArgIndex = 0;
721 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000722 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
723 e = FT->param_type_end();
724 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000725 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
726 SourceLocation ParamLoc = PD->getLocation();
727 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000728 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000729 diag::err_constexpr_non_literal_param,
730 ArgIndex+1, PD->getSourceRange(),
731 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000732 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000733 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000734 return true;
735}
736
737/// \brief Get diagnostic %select index for tag kind for
738/// record diagnostic message.
739/// WARNING: Indexes apply to particular diagnostics only!
740///
741/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000742static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000743 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000744 case TTK_Struct: return 0;
745 case TTK_Interface: return 1;
746 case TTK_Class: return 2;
747 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000748 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000749}
750
751// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
752// the requirements of a constexpr function definition or a constexpr
753// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000754// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000755//
Richard Smith3607ffe2012-02-13 03:54:03 +0000756// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
757bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000758 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
759 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000760 // C++11 [dcl.constexpr]p4:
761 // The definition of a constexpr constructor shall satisfy the following
762 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000763 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000764 const CXXRecordDecl *RD = MD->getParent();
765 if (RD->getNumVBases()) {
766 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
767 << isa<CXXConstructorDecl>(NewFD)
768 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000769 for (const auto &I : RD->vbases())
770 Diag(I.getLocStart(),
771 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000772 return false;
773 }
Richard Smith7971b692012-01-13 04:54:00 +0000774 }
775
776 if (!isa<CXXConstructorDecl>(NewFD)) {
777 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000778 // The definition of a constexpr function shall satisfy the following
779 // constraints:
780 // - it shall not be virtual;
781 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
782 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000783 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000784
Richard Smith3607ffe2012-02-13 03:54:03 +0000785 // If it's not obvious why this function is virtual, find an overridden
786 // function which uses the 'virtual' keyword.
787 const CXXMethodDecl *WrittenVirtual = Method;
788 while (!WrittenVirtual->isVirtualAsWritten())
789 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
790 if (WrittenVirtual != Method)
791 Diag(WrittenVirtual->getLocation(),
792 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000793 return false;
794 }
795
796 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000797 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000798 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000799 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000800 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 }
803
Richard Smith7971b692012-01-13 04:54:00 +0000804 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000805 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000806 return false;
807
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808 return true;
809}
810
811/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000812/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000813///
Richard Smithd9f663b2013-04-22 15:31:51 +0000814/// \return true if the body is OK (maybe only as an extension), false if we
815/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000817 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
818 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000819 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
820 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000821 for (const auto *DclIt : DS->decls()) {
822 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000823 case Decl::StaticAssert:
824 case Decl::Using:
825 case Decl::UsingShadow:
826 case Decl::UsingDirective:
827 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000828 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000829 // - static_assert-declarations
830 // - using-declarations,
831 // - using-directives,
832 continue;
833
834 case Decl::Typedef:
835 case Decl::TypeAlias: {
836 // - typedef declarations and alias-declarations that do not define
837 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000838 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000839 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
840 // Don't allow variably-modified types in constexpr functions.
841 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
842 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
843 << TL.getSourceRange() << TL.getType()
844 << isa<CXXConstructorDecl>(Dcl);
845 return false;
846 }
847 continue;
848 }
849
850 case Decl::Enum:
851 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000852 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000853 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000854 SemaRef.Diag(DS->getLocStart(),
855 SemaRef.getLangOpts().CPlusPlus1y
856 ? diag::warn_cxx11_compat_constexpr_type_definition
857 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000858 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000859 continue;
860
Richard Smithd9f663b2013-04-22 15:31:51 +0000861 case Decl::EnumConstant:
862 case Decl::IndirectField:
863 case Decl::ParmVar:
864 // These can only appear with other declarations which are banned in
865 // C++11 and permitted in C++1y, so ignore them.
866 continue;
867
868 case Decl::Var: {
869 // C++1y [dcl.constexpr]p3 allows anything except:
870 // a definition of a variable of non-literal type or of static or
871 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000872 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000873 if (VD->isThisDeclarationADefinition()) {
874 if (VD->isStaticLocal()) {
875 SemaRef.Diag(VD->getLocation(),
876 diag::err_constexpr_local_var_static)
877 << isa<CXXConstructorDecl>(Dcl)
878 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
879 return false;
880 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000881 if (!VD->getType()->isDependentType() &&
882 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000883 VD->getLocation(), VD->getType(),
884 diag::err_constexpr_local_var_non_literal_type,
885 isa<CXXConstructorDecl>(Dcl)))
886 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000887 if (!VD->getType()->isDependentType() &&
888 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000889 SemaRef.Diag(VD->getLocation(),
890 diag::err_constexpr_local_var_no_init)
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894 }
895 SemaRef.Diag(VD->getLocation(),
896 SemaRef.getLangOpts().CPlusPlus1y
897 ? diag::warn_cxx11_compat_constexpr_local_var
898 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000899 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000900 continue;
901 }
902
903 case Decl::NamespaceAlias:
904 case Decl::Function:
905 // These are disallowed in C++11 and permitted in C++1y. Allow them
906 // everywhere as an extension.
907 if (!Cxx1yLoc.isValid())
908 Cxx1yLoc = DS->getLocStart();
909 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000910
911 default:
912 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
913 << isa<CXXConstructorDecl>(Dcl);
914 return false;
915 }
916 }
917
918 return true;
919}
920
921/// Check that the given field is initialized within a constexpr constructor.
922///
923/// \param Dcl The constexpr constructor being checked.
924/// \param Field The field being checked. This may be a member of an anonymous
925/// struct or union nested within the class being checked.
926/// \param Inits All declarations, including anonymous struct/union members and
927/// indirect members, for which any initialization was provided.
928/// \param Diagnosed Set to true if an error is produced.
929static void CheckConstexprCtorInitializer(Sema &SemaRef,
930 const FunctionDecl *Dcl,
931 FieldDecl *Field,
932 llvm::SmallSet<Decl*, 16> &Inits,
933 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000934 if (Field->isInvalidDecl())
935 return;
936
Douglas Gregor556e5862011-10-10 17:22:13 +0000937 if (Field->isUnnamedBitfield())
938 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000939
Richard Smithab44d5b2013-12-10 08:25:00 +0000940 // Anonymous unions with no variant members and empty anonymous structs do not
941 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
942 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000943 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000944 (Field->getType()->isUnionType()
945 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
946 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000947 return;
948
Richard Smitheb3c10c2011-10-01 02:31:28 +0000949 if (!Inits.count(Field)) {
950 if (!Diagnosed) {
951 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
952 Diagnosed = true;
953 }
954 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
955 } else if (Field->isAnonymousStructOrUnion()) {
956 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000957 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000958 // If an anonymous union contains an anonymous struct of which any member
959 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000960 if (!RD->isUnion() || Inits.count(I))
961 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000962 }
963}
964
Richard Smithd9f663b2013-04-22 15:31:51 +0000965/// Check the provided statement is allowed in a constexpr function
966/// definition.
967static bool
968CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000969 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000970 SourceLocation &Cxx1yLoc) {
971 // - its function-body shall be [...] a compound-statement that contains only
972 switch (S->getStmtClass()) {
973 case Stmt::NullStmtClass:
974 // - null statements,
975 return true;
976
977 case Stmt::DeclStmtClass:
978 // - static_assert-declarations
979 // - using-declarations,
980 // - using-directives,
981 // - typedef declarations and alias-declarations that do not define
982 // classes or enumerations,
983 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
984 return false;
985 return true;
986
987 case Stmt::ReturnStmtClass:
988 // - and exactly one return statement;
989 if (isa<CXXConstructorDecl>(Dcl)) {
990 // C++1y allows return statements in constexpr constructors.
991 if (!Cxx1yLoc.isValid())
992 Cxx1yLoc = S->getLocStart();
993 return true;
994 }
995
996 ReturnStmts.push_back(S->getLocStart());
997 return true;
998
999 case Stmt::CompoundStmtClass: {
1000 // C++1y allows compound-statements.
1001 if (!Cxx1yLoc.isValid())
1002 Cxx1yLoc = S->getLocStart();
1003
1004 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001005 for (auto *BodyIt : CompStmt->body()) {
1006 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001007 Cxx1yLoc))
1008 return false;
1009 }
1010 return true;
1011 }
1012
1013 case Stmt::AttributedStmtClass:
1014 if (!Cxx1yLoc.isValid())
1015 Cxx1yLoc = S->getLocStart();
1016 return true;
1017
1018 case Stmt::IfStmtClass: {
1019 // C++1y allows if-statements.
1020 if (!Cxx1yLoc.isValid())
1021 Cxx1yLoc = S->getLocStart();
1022
1023 IfStmt *If = cast<IfStmt>(S);
1024 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1025 Cxx1yLoc))
1026 return false;
1027 if (If->getElse() &&
1028 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1029 Cxx1yLoc))
1030 return false;
1031 return true;
1032 }
1033
1034 case Stmt::WhileStmtClass:
1035 case Stmt::DoStmtClass:
1036 case Stmt::ForStmtClass:
1037 case Stmt::CXXForRangeStmtClass:
1038 case Stmt::ContinueStmtClass:
1039 // C++1y allows all of these. We don't allow them as extensions in C++11,
1040 // because they don't make sense without variable mutation.
1041 if (!SemaRef.getLangOpts().CPlusPlus1y)
1042 break;
1043 if (!Cxx1yLoc.isValid())
1044 Cxx1yLoc = S->getLocStart();
1045 for (Stmt::child_range Children = S->children(); Children; ++Children)
1046 if (*Children &&
1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048 Cxx1yLoc))
1049 return false;
1050 return true;
1051
1052 case Stmt::SwitchStmtClass:
1053 case Stmt::CaseStmtClass:
1054 case Stmt::DefaultStmtClass:
1055 case Stmt::BreakStmtClass:
1056 // C++1y allows switch-statements, and since they don't need variable
1057 // mutation, we can reasonably allow them in C++11 as an extension.
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 for (Stmt::child_range Children = S->children(); Children; ++Children)
1061 if (*Children &&
1062 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063 Cxx1yLoc))
1064 return false;
1065 return true;
1066
1067 default:
1068 if (!isa<Expr>(S))
1069 break;
1070
1071 // C++1y allows expression-statements.
1072 if (!Cxx1yLoc.isValid())
1073 Cxx1yLoc = S->getLocStart();
1074 return true;
1075 }
1076
1077 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1078 << isa<CXXConstructorDecl>(Dcl);
1079 return false;
1080}
1081
Richard Smitheb3c10c2011-10-01 02:31:28 +00001082/// Check the body for the given constexpr function declaration only contains
1083/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1084///
1085/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001086bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001087 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001088 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001089 // The definition of a constexpr function shall satisfy the following
1090 // constraints: [...]
1091 // - its function-body shall be = delete, = default, or a
1092 // compound-statement
1093 //
Richard Smith74388b42012-02-04 00:33:54 +00001094 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001095 // In the definition of a constexpr constructor, [...]
1096 // - its function-body shall not be a function-try-block;
1097 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1098 << isa<CXXConstructorDecl>(Dcl);
1099 return false;
1100 }
1101
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001102 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001103
1104 // - its function-body shall be [...] a compound-statement that contains only
1105 // [... list of cases ...]
1106 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1107 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001108 for (auto *BodyIt : CompBody->body()) {
1109 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001110 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001111 }
1112
Richard Smithd9f663b2013-04-22 15:31:51 +00001113 if (Cxx1yLoc.isValid())
1114 Diag(Cxx1yLoc,
1115 getLangOpts().CPlusPlus1y
1116 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1117 : diag::ext_constexpr_body_invalid_stmt)
1118 << isa<CXXConstructorDecl>(Dcl);
1119
Richard Smitheb3c10c2011-10-01 02:31:28 +00001120 if (const CXXConstructorDecl *Constructor
1121 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1122 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001123 // DR1359:
1124 // - every non-variant non-static data member and base class sub-object
1125 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001126 // DR1460:
1127 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001128 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001130 if (Constructor->getNumCtorInitializers() == 0 &&
1131 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001132 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1133 return false;
1134 }
Richard Smithf368fb42011-10-10 16:38:04 +00001135 } else if (!Constructor->isDependentContext() &&
1136 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001137 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1138
1139 // Skip detailed checking if we have enough initializers, and we would
1140 // allow at most one initializer per member.
1141 bool AnyAnonStructUnionMembers = false;
1142 unsigned Fields = 0;
1143 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1144 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001145 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001146 AnyAnonStructUnionMembers = true;
1147 break;
1148 }
1149 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001150 // DR1460:
1151 // - if the class is a union-like class, but is not a union, for each of
1152 // its anonymous union members having variant members, exactly one of
1153 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001154 if (AnyAnonStructUnionMembers ||
1155 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1156 // Check initialization of non-static data members. Base classes are
1157 // always initialized so do not need to be checked. Dependent bases
1158 // might not have initializers in the member initializer list.
1159 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001160 for (const auto *I: Constructor->inits()) {
1161 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001162 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001163 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001164 Inits.insert(ID->chain_begin(), ID->chain_end());
1165 }
1166
1167 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001168 for (auto *I : RD->fields())
1169 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001170 if (Diagnosed)
1171 return false;
1172 }
1173 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001174 } else {
1175 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001176 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001177 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001178 // otherwise if there's no return statement, the function cannot
1179 // be used in a core constant expression.
Richard Smith06ffb452014-04-22 23:14:23 +00001180 bool OK = getLangOpts().CPlusPlus1y &&
1181 (Dcl->getReturnType()->isVoidType() ||
1182 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001183 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001184 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1185 : diag::err_constexpr_body_no_return);
1186 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001187 }
1188 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001189 Diag(ReturnStmts.back(),
1190 getLangOpts().CPlusPlus1y
1191 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1192 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001193 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1194 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001195 }
1196 }
1197
Richard Smith74388b42012-02-04 00:33:54 +00001198 // C++11 [dcl.constexpr]p5:
1199 // if no function argument values exist such that the function invocation
1200 // substitution would produce a constant expression, the program is
1201 // ill-formed; no diagnostic required.
1202 // C++11 [dcl.constexpr]p3:
1203 // - every constructor call and implicit conversion used in initializing the
1204 // return value shall be one of those allowed in a constant expression.
1205 // C++11 [dcl.constexpr]p4:
1206 // - every constructor involved in initializing non-static data members and
1207 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001208 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001209 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001210 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001211 << isa<CXXConstructorDecl>(Dcl);
1212 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1213 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001214 // Don't return false here: we allow this for compatibility in
1215 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001216 }
1217
Richard Smitheb3c10c2011-10-01 02:31:28 +00001218 return true;
1219}
1220
Douglas Gregor61956c42008-10-31 09:07:45 +00001221/// isCurrentClassName - Determine whether the identifier II is the
1222/// name of the class type currently being defined. In the case of
1223/// nested classes, this will only return true if II is the name of
1224/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001225bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1226 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001227 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001228
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001229 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001230 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001231 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001232 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1233 } else
1234 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1235
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001236 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001237 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001238 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001239}
1240
Richard Smithfb8b7b92013-10-15 00:00:26 +00001241/// \brief Determine whether the identifier II is a typo for the name of
1242/// the class type currently being defined. If so, update it to the identifier
1243/// that should have been used.
1244bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1245 assert(getLangOpts().CPlusPlus && "No class names in C!");
1246
1247 if (!getLangOpts().SpellChecking)
1248 return false;
1249
1250 CXXRecordDecl *CurDecl;
1251 if (SS && SS->isSet() && !SS->isInvalid()) {
1252 DeclContext *DC = computeDeclContext(*SS, true);
1253 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1254 } else
1255 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1256
1257 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1258 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1259 < II->getLength()) {
1260 II = CurDecl->getIdentifier();
1261 return true;
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregordc974572012-11-10 07:24:09 +00001267/// \brief Determine whether the given class is a base class of the given
1268/// class, including looking at dependent bases.
1269static bool findCircularInheritance(const CXXRecordDecl *Class,
1270 const CXXRecordDecl *Current) {
1271 SmallVector<const CXXRecordDecl*, 8> Queue;
1272
1273 Class = Class->getCanonicalDecl();
1274 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001275 for (const auto &I : Current->bases()) {
1276 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001277 if (!Base)
1278 continue;
1279
1280 Base = Base->getDefinition();
1281 if (!Base)
1282 continue;
1283
1284 if (Base->getCanonicalDecl() == Class)
1285 return true;
1286
1287 Queue.push_back(Base);
1288 }
1289
1290 if (Queue.empty())
1291 return false;
1292
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001293 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001294 }
1295
1296 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001297}
1298
Mike Stump11289f42009-09-09 15:08:12 +00001299/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001300///
1301/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1302/// and returns NULL otherwise.
1303CXXBaseSpecifier *
1304Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1305 SourceRange SpecifierRange,
1306 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001307 TypeSourceInfo *TInfo,
1308 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001309 QualType BaseType = TInfo->getType();
1310
Douglas Gregor463421d2009-03-03 04:44:36 +00001311 // C++ [class.union]p1:
1312 // A union shall not have base classes.
1313 if (Class->isUnion()) {
1314 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1315 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001316 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001317 }
1318
Douglas Gregor752a5952011-01-03 22:36:02 +00001319 if (EllipsisLoc.isValid() &&
1320 !TInfo->getType()->containsUnexpandedParameterPack()) {
1321 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1322 << TInfo->getTypeLoc().getSourceRange();
1323 EllipsisLoc = SourceLocation();
1324 }
Douglas Gregor62004702012-11-10 01:18:17 +00001325
1326 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1327
1328 if (BaseType->isDependentType()) {
1329 // Make sure that we don't have circular inheritance among our dependent
1330 // bases. For non-dependent bases, the check for completeness below handles
1331 // this.
1332 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1333 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1334 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001335 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001336 Diag(BaseLoc, diag::err_circular_inheritance)
1337 << BaseType << Context.getTypeDeclType(Class);
1338
1339 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1340 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1341 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001342
1343 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001344 }
1345 }
1346
Mike Stump11289f42009-09-09 15:08:12 +00001347 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001348 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001349 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001350 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001351
1352 // Base specifiers must be record types.
1353 if (!BaseType->isRecordType()) {
1354 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001355 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001356 }
1357
1358 // C++ [class.union]p1:
1359 // A union shall not be used as a base class.
1360 if (BaseType->isUnionType()) {
1361 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001362 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001363 }
1364
1365 // C++ [class.derived]p2:
1366 // The class-name in a base-specifier shall not be an incompletely
1367 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001368 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001369 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001370 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001371 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001372 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001373
Eli Friedmanc96d4962009-08-15 21:55:26 +00001374 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001375 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001376 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001377 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001378 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001379 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001380 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001381
David Majnemer9b1754d2013-11-02 12:00:36 +00001382 // A class which contains a flexible array member is not suitable for use as a
1383 // base class:
1384 // - If the layout determines that a base comes before another base,
1385 // the flexible array member would index into the subsequent base.
1386 // - If the layout determines that base comes before the derived class,
1387 // the flexible array member would index into the derived class.
1388 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1389 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1390 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001391 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001392 }
1393
Anders Carlsson65c76d32011-03-25 14:55:14 +00001394 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001395 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001396 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001397 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001398 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001399 << CXXBaseDecl->getDeclName()
1400 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001401 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1402 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001403 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001404 }
1405
John McCall3696dcb2010-08-17 07:23:57 +00001406 if (BaseDecl->isInvalidDecl())
1407 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001408
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001409 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001410 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001411 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001412 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001413}
1414
Douglas Gregor556877c2008-04-13 21:30:24 +00001415/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1416/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001417/// example:
1418/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001419/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001420BaseResult
John McCall48871652010-08-21 09:40:31 +00001421Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001422 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001423 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001424 ParsedType basetype, SourceLocation BaseLoc,
1425 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001426 if (!classdecl)
1427 return true;
1428
Douglas Gregorc40290e2009-03-09 23:48:35 +00001429 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001430 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001431 if (!Class)
1432 return true;
1433
David Majnemer5ef4fe72014-06-13 06:43:46 +00001434 // We haven't yet attached the base specifiers.
1435 Class->setIsParsingBaseSpecifiers();
1436
Richard Smith4c96e992013-02-19 23:47:15 +00001437 // We do not support any C++11 attributes on base-specifiers yet.
1438 // Diagnose any attributes we see.
1439 if (!Attributes.empty()) {
1440 for (AttributeList *Attr = Attributes.getList(); Attr;
1441 Attr = Attr->getNext()) {
1442 if (Attr->isInvalid() ||
1443 Attr->getKind() == AttributeList::IgnoredAttribute)
1444 continue;
1445 Diag(Attr->getLoc(),
1446 Attr->getKind() == AttributeList::UnknownAttribute
1447 ? diag::warn_unknown_attribute_ignored
1448 : diag::err_base_specifier_attribute)
1449 << Attr->getName();
1450 }
1451 }
1452
Craig Topperc3ec1492014-05-26 06:22:03 +00001453 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001454 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001455
Douglas Gregor752a5952011-01-03 22:36:02 +00001456 if (EllipsisLoc.isInvalid() &&
1457 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001458 UPPC_BaseType))
1459 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001460
Douglas Gregor463421d2009-03-03 04:44:36 +00001461 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001462 Virtual, Access, TInfo,
1463 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001464 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001465 else
1466 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001467
Douglas Gregor463421d2009-03-03 04:44:36 +00001468 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001469}
Douglas Gregor556877c2008-04-13 21:30:24 +00001470
Douglas Gregor463421d2009-03-03 04:44:36 +00001471/// \brief Performs the actual work of attaching the given base class
1472/// specifiers to a C++ class.
1473bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1474 unsigned NumBases) {
1475 if (NumBases == 0)
1476 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001477
1478 // Used to keep track of which base types we have already seen, so
1479 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001480 // that the key is always the unqualified canonical type of the base
1481 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001482 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1483
1484 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001485 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001486 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001487 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001488 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001489 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001490 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001491
1492 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1493 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001494 // C++ [class.mi]p3:
1495 // A class shall not be specified as a direct base class of a
1496 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001497 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001498 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001499 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001500 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001501
1502 // Delete the duplicate base class specifier; we're going to
1503 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001504 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001505
1506 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001507 } else {
1508 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001509 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001510 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001511 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1512 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1513 if (Class->isInterface() &&
1514 (!RD->isInterface() ||
1515 KnownBase->getAccessSpecifier() != AS_public)) {
1516 // The Microsoft extension __interface does not permit bases that
1517 // are not themselves public interfaces.
1518 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1519 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1520 << RD->getSourceRange();
1521 Invalid = true;
1522 }
1523 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001524 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001525 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001526 }
1527 }
1528
1529 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001530 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001531
1532 // Delete the remaining (good) base class specifiers, since their
1533 // data has been copied into the CXXRecordDecl.
1534 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001535 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001536
1537 return Invalid;
1538}
1539
1540/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1541/// class, after checking whether there are any duplicate base
1542/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001543void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001544 unsigned NumBases) {
1545 if (!ClassDecl || !Bases || !NumBases)
1546 return;
1547
1548 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001549 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001550}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001551
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552/// \brief Determine whether the type \p Derived is a C++ class that is
1553/// derived from the type \p Base.
1554bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001555 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001556 return false;
John McCalle78aac42010-03-10 03:28:59 +00001557
Douglas Gregor45bb4832013-03-26 23:36:30 +00001558 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001559 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001560 return false;
1561
Douglas Gregor45bb4832013-03-26 23:36:30 +00001562 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001563 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001564 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001565
1566 // If either the base or the derived type is invalid, don't try to
1567 // check whether one is derived from the other.
1568 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1569 return false;
1570
John McCall67da35c2010-02-04 22:26:26 +00001571 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1572 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001573}
1574
1575/// \brief Determine whether the type \p Derived is a C++ class that is
1576/// derived from the type \p Base.
1577bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001579 return false;
1580
Douglas Gregor45bb4832013-03-26 23:36:30 +00001581 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001582 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001583 return false;
1584
Douglas Gregor45bb4832013-03-26 23:36:30 +00001585 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001586 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001587 return false;
1588
Douglas Gregor36d1b142009-10-06 17:59:45 +00001589 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1590}
1591
Anders Carlssona70cff62010-04-24 19:06:50 +00001592void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001593 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001594 assert(BasePathArray.empty() && "Base path array must be empty!");
1595 assert(Paths.isRecordingPaths() && "Must record paths!");
1596
1597 const CXXBasePath &Path = Paths.front();
1598
1599 // We first go backward and check if we have a virtual base.
1600 // FIXME: It would be better if CXXBasePath had the base specifier for
1601 // the nearest virtual base.
1602 unsigned Start = 0;
1603 for (unsigned I = Path.size(); I != 0; --I) {
1604 if (Path[I - 1].Base->isVirtual()) {
1605 Start = I - 1;
1606 break;
1607 }
1608 }
1609
1610 // Now add all bases.
1611 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001612 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001613}
1614
Douglas Gregor88d292c2010-05-13 16:44:06 +00001615/// \brief Determine whether the given base path includes a virtual
1616/// base class.
John McCallcf142162010-08-07 06:22:56 +00001617bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1618 for (CXXCastPath::const_iterator B = BasePath.begin(),
1619 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001620 B != BEnd; ++B)
1621 if ((*B)->isVirtual())
1622 return true;
1623
1624 return false;
1625}
1626
Douglas Gregor36d1b142009-10-06 17:59:45 +00001627/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1628/// conversion (where Derived and Base are class types) is
1629/// well-formed, meaning that the conversion is unambiguous (and
1630/// that all of the base classes are accessible). Returns true
1631/// and emits a diagnostic if the code is ill-formed, returns false
1632/// otherwise. Loc is the location where this routine should point to
1633/// if there is an error, and Range is the source range to highlight
1634/// if there is an error.
1635bool
1636Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001637 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638 unsigned AmbigiousBaseConvID,
1639 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001640 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001641 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001642 // First, determine whether the path from Derived to Base is
1643 // ambiguous. This is slightly more expensive than checking whether
1644 // the Derived to Base conversion exists, because here we need to
1645 // explore multiple paths to determine if there is an ambiguity.
1646 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1647 /*DetectVirtual=*/false);
1648 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1649 assert(DerivationOkay &&
1650 "Can only be used with a derived-to-base conversion");
1651 (void)DerivationOkay;
1652
1653 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001654 if (InaccessibleBaseID) {
1655 // Check that the base class can be accessed.
1656 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1657 InaccessibleBaseID)) {
1658 case AR_inaccessible:
1659 return true;
1660 case AR_accessible:
1661 case AR_dependent:
1662 case AR_delayed:
1663 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001664 }
John McCall5b0829a2010-02-10 09:31:12 +00001665 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001666
1667 // Build a base path if necessary.
1668 if (BasePath)
1669 BuildBasePathArray(Paths, *BasePath);
1670 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001671 }
1672
David Majnemer626032f2013-06-22 06:43:58 +00001673 if (AmbigiousBaseConvID) {
1674 // We know that the derived-to-base conversion is ambiguous, and
1675 // we're going to produce a diagnostic. Perform the derived-to-base
1676 // search just one more time to compute all of the possible paths so
1677 // that we can print them out. This is more expensive than any of
1678 // the previous derived-to-base checks we've done, but at this point
1679 // performance isn't as much of an issue.
1680 Paths.clear();
1681 Paths.setRecordingPaths(true);
1682 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1683 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1684 (void)StillOkay;
1685
1686 // Build up a textual representation of the ambiguous paths, e.g.,
1687 // D -> B -> A, that will be used to illustrate the ambiguous
1688 // conversions in the diagnostic. We only print one of the paths
1689 // to each base class subobject.
1690 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1691
1692 Diag(Loc, AmbigiousBaseConvID)
1693 << Derived << Base << PathDisplayStr << Range << Name;
1694 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001695 return true;
1696}
1697
1698bool
1699Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001700 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001701 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001702 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001704 IgnoreAccess ? 0
1705 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001706 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001707 Loc, Range, DeclarationName(),
1708 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709}
1710
1711
1712/// @brief Builds a string representing ambiguous paths from a
1713/// specific derived class to different subobjects of the same base
1714/// class.
1715///
1716/// This function builds a string that can be used in error messages
1717/// to show the different paths that one can take through the
1718/// inheritance hierarchy to go from the derived class to different
1719/// subobjects of a base class. The result looks something like this:
1720/// @code
1721/// struct D -> struct B -> struct A
1722/// struct D -> struct C -> struct A
1723/// @endcode
1724std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1725 std::string PathDisplayStr;
1726 std::set<unsigned> DisplayedPaths;
1727 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1728 Path != Paths.end(); ++Path) {
1729 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1730 // We haven't displayed a path to this particular base
1731 // class subobject yet.
1732 PathDisplayStr += "\n ";
1733 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1734 for (CXXBasePath::const_iterator Element = Path->begin();
1735 Element != Path->end(); ++Element)
1736 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1737 }
1738 }
1739
1740 return PathDisplayStr;
1741}
1742
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001743//===----------------------------------------------------------------------===//
1744// C++ class member Handling
1745//===----------------------------------------------------------------------===//
1746
Abramo Bagnarad7340582010-06-05 05:09:32 +00001747/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001748bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1749 SourceLocation ASLoc,
1750 SourceLocation ColonLoc,
1751 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001752 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001753 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001754 ASLoc, ColonLoc);
1755 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001756 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001757}
1758
Richard Smith18f07db2012-08-06 03:25:17 +00001759/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001760void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001761 if (D->isInvalidDecl())
1762 return;
1763
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001764 // We only care about "override" and "final" declarations.
1765 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1766 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001767
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001768 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001769
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001770 // We can't check dependent instance methods.
1771 if (MD && MD->isInstance() &&
1772 (MD->getParent()->hasAnyDependentBases() ||
1773 MD->getType()->isDependentType()))
1774 return;
1775
1776 if (MD && !MD->isVirtual()) {
1777 // If we have a non-virtual method, check if if hides a virtual method.
1778 // (In that case, it's most likely the method has the wrong type.)
1779 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1780 FindHiddenVirtualMethods(MD, OverloadedMethods);
1781
1782 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001783 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1784 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001785 diag::override_keyword_hides_virtual_member_function)
1786 << "override" << (OverloadedMethods.size() > 1);
1787 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001788 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001789 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001790 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1791 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001792 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001793 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1794 MD->setInvalidDecl();
1795 return;
1796 }
1797 // Fall through into the general case diagnostic.
1798 // FIXME: We might want to attempt typo correction here.
1799 }
1800
1801 if (!MD || !MD->isVirtual()) {
1802 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1803 Diag(OA->getLocation(),
1804 diag::override_keyword_only_allowed_on_virtual_member_functions)
1805 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1806 D->dropAttr<OverrideAttr>();
1807 }
1808 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1809 Diag(FA->getLocation(),
1810 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001811 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1812 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001813 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001814 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001815 return;
1816 }
Richard Smith18f07db2012-08-06 03:25:17 +00001817
Richard Smith18f07db2012-08-06 03:25:17 +00001818 // C++11 [class.virtual]p5:
1819 // If a virtual function is marked with the virt-specifier override and
1820 // does not override a member function of a base class, the program is
1821 // ill-formed.
1822 bool HasOverriddenMethods =
1823 MD->begin_overridden_methods() != MD->end_overridden_methods();
1824 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1825 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1826 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001827}
1828
Richard Smith18f07db2012-08-06 03:25:17 +00001829/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001830/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001831/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001832bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1833 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001834 FinalAttr *FA = Old->getAttr<FinalAttr>();
1835 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001836 return false;
1837
1838 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001839 << New->getDeclName()
1840 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001841 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1842 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001843}
1844
Daniel Jasper0baec5492012-06-06 08:32:04 +00001845static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001846 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1847 // FIXME: Destruction of ObjC lifetime types has side-effects.
1848 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1849 return !RD->isCompleteDefinition() ||
1850 !RD->hasTrivialDefaultConstructor() ||
1851 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001852 return false;
1853}
1854
John McCall5e77d762013-04-16 07:28:30 +00001855static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001856 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001857 if (it->isDeclspecPropertyAttribute())
1858 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001859 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001860}
1861
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001862/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1863/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001864/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001865/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1866/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001867NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001868Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001869 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001870 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001871 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001872 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001873 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1874 DeclarationName Name = NameInfo.getName();
1875 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001876
1877 // For anonymous bitfields, the location should point to the type.
1878 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001879 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001880
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001881 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001882
John McCallb1cd7da2010-06-04 08:34:12 +00001883 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001884 assert(!DS.isFriendSpecified());
1885
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001886 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001887
John McCalldb632ac2012-09-25 07:32:39 +00001888 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1889 // The Microsoft extension __interface only permits public member functions
1890 // and prohibits constructors, destructors, operators, non-public member
1891 // functions, static methods and data members.
1892 unsigned InvalidDecl;
1893 bool ShowDeclName = true;
1894 if (!isFunc)
1895 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1896 else if (AS != AS_public)
1897 InvalidDecl = 2;
1898 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1899 InvalidDecl = 3;
1900 else switch (Name.getNameKind()) {
1901 case DeclarationName::CXXConstructorName:
1902 InvalidDecl = 4;
1903 ShowDeclName = false;
1904 break;
1905
1906 case DeclarationName::CXXDestructorName:
1907 InvalidDecl = 5;
1908 ShowDeclName = false;
1909 break;
1910
1911 case DeclarationName::CXXOperatorName:
1912 case DeclarationName::CXXConversionFunctionName:
1913 InvalidDecl = 6;
1914 break;
1915
1916 default:
1917 InvalidDecl = 0;
1918 break;
1919 }
1920
1921 if (InvalidDecl) {
1922 if (ShowDeclName)
1923 Diag(Loc, diag::err_invalid_member_in_interface)
1924 << (InvalidDecl-1) << Name;
1925 else
1926 Diag(Loc, diag::err_invalid_member_in_interface)
1927 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00001928 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00001929 }
1930 }
1931
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001932 // C++ 9.2p6: A member shall not be declared to have automatic storage
1933 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001934 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1935 // data members and cannot be applied to names declared const or static,
1936 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001937 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001938 case DeclSpec::SCS_unspecified:
1939 case DeclSpec::SCS_typedef:
1940 case DeclSpec::SCS_static:
1941 break;
1942 case DeclSpec::SCS_mutable:
1943 if (isFunc) {
1944 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Richard Smithb4a9e862013-04-12 22:46:28 +00001946 // FIXME: It would be nicer if the keyword was ignored only for this
1947 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001948 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001949 }
1950 break;
1951 default:
1952 Diag(DS.getStorageClassSpecLoc(),
1953 diag::err_storageclass_invalid_for_member);
1954 D.getMutableDeclSpec().ClearStorageClassSpecs();
1955 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001956 }
1957
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001958 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1959 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001960 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001961
David Blaikie35506f82013-01-30 01:22:18 +00001962 if (DS.isConstexprSpecified() && isInstField) {
1963 SemaDiagnosticBuilder B =
1964 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1965 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1966 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00001967 B << 0 << 0;
1968 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1969 B << FixItHint::CreateRemoval(ConstexprLoc);
1970 else {
1971 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1972 D.getMutableDeclSpec().ClearConstexprSpec();
1973 const char *PrevSpec;
1974 unsigned DiagID;
1975 bool Failed = D.getMutableDeclSpec().SetTypeQual(
1976 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1977 (void)Failed;
1978 assert(!Failed && "Making a constexpr member const shouldn't fail");
1979 }
David Blaikie35506f82013-01-30 01:22:18 +00001980 } else {
1981 B << 1;
1982 const char *PrevSpec;
1983 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001984 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001985 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1986 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001987 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001988 "This is the only DeclSpec that should fail to be applied");
1989 B << 1;
1990 } else {
1991 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1992 isInstField = false;
1993 }
1994 }
1995 }
1996
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001997 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001998 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001999 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002000
2001 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002002 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002003 Diag(Loc, diag::err_bad_variable_name)
2004 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002005 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002006 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002007
Benjamin Kramer365082d2012-05-19 16:34:46 +00002008 IdentifierInfo *II = Name.getAsIdentifierInfo();
2009
Douglas Gregor7c26c042011-09-21 14:40:46 +00002010 // Member field could not be with "template" keyword.
2011 // So TemplateParameterLists should be empty in this case.
2012 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002013 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002014 if (TemplateParams->size()) {
2015 // There is no such thing as a member field template.
2016 Diag(D.getIdentifierLoc(), diag::err_template_member)
2017 << II
2018 << SourceRange(TemplateParams->getTemplateLoc(),
2019 TemplateParams->getRAngleLoc());
2020 } else {
2021 // There is an extraneous 'template<>' for this member.
2022 Diag(TemplateParams->getTemplateLoc(),
2023 diag::err_template_member_noparams)
2024 << II
2025 << SourceRange(TemplateParams->getTemplateLoc(),
2026 TemplateParams->getRAngleLoc());
2027 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002028 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002029 }
2030
Douglas Gregora007d362010-10-13 22:19:53 +00002031 if (SS.isSet() && !SS.isInvalid()) {
2032 // The user provided a superfluous scope specifier inside a class
2033 // definition:
2034 //
2035 // class X {
2036 // int X::member;
2037 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002038 if (DeclContext *DC = computeDeclContext(SS, false))
2039 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002040 else
2041 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2042 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002043
Douglas Gregora007d362010-10-13 22:19:53 +00002044 SS.clear();
2045 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002046
John McCall5e77d762013-04-16 07:28:30 +00002047 AttributeList *MSPropertyAttr =
2048 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002049 if (MSPropertyAttr) {
2050 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2051 BitWidth, InitStyle, AS, MSPropertyAttr);
2052 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002053 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002054 isInstField = false;
2055 } else {
2056 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2057 BitWidth, InitStyle, AS);
2058 assert(Member && "HandleField never returns null");
2059 }
2060 } else {
2061 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2062
2063 Member = HandleDeclarator(S, D, TemplateParameterLists);
2064 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002065 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002066
2067 // Non-instance-fields can't have a bitfield.
2068 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002069 if (Member->isInvalidDecl()) {
2070 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002071 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002072 // C++ 9.6p3: A bit-field shall not be a static member.
2073 // "static member 'A' cannot be a bit-field"
2074 Diag(Loc, diag::err_static_not_bitfield)
2075 << Name << BitWidth->getSourceRange();
2076 } else if (isa<TypedefDecl>(Member)) {
2077 // "typedef member 'x' cannot be a bit-field"
2078 Diag(Loc, diag::err_typedef_not_bitfield)
2079 << Name << BitWidth->getSourceRange();
2080 } else {
2081 // A function typedef ("typedef int f(); f a;").
2082 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2083 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002084 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002085 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002086 }
Mike Stump11289f42009-09-09 15:08:12 +00002087
Craig Topperc3ec1492014-05-26 06:22:03 +00002088 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002089 Member->setInvalidDecl();
2090 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002091
2092 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002093
Larisse Voufo39a1e502013-08-06 01:03:05 +00002094 // If we have declared a member function template or static data member
2095 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002096 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2097 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002098 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2099 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002100 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002101
Richard Smith18f07db2012-08-06 03:25:17 +00002102 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002103 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002104 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002105 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2106 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002107
Douglas Gregorf2f08062011-03-08 17:10:18 +00002108 if (VS.getLastLocation().isValid()) {
2109 // Update the end location of a method that has a virt-specifiers.
2110 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2111 MD->setRangeEnd(VS.getLastLocation());
2112 }
Richard Smith18f07db2012-08-06 03:25:17 +00002113
Anders Carlssonc87f8612011-01-20 06:29:02 +00002114 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002115
Douglas Gregor92751d42008-11-17 22:58:34 +00002116 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002117
Daniel Jasper0baec5492012-06-06 08:32:04 +00002118 if (isInstField) {
2119 FieldDecl *FD = cast<FieldDecl>(Member);
2120 FieldCollector->Add(FD);
2121
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002122 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002123 // Remember all explicit private FieldDecls that have a name, no side
2124 // effects and are not part of a dependent type declaration.
2125 if (!FD->isImplicit() && FD->getDeclName() &&
2126 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002127 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002128 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002129 !InitializationHasSideEffects(*FD))
2130 UnusedPrivateFields.insert(FD);
2131 }
2132 }
2133
John McCall48871652010-08-21 09:40:31 +00002134 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002135}
2136
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002137namespace {
2138 class UninitializedFieldVisitor
2139 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2140 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002141 // List of Decls to generate a warning on. Also remove Decls that become
2142 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002143 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002144 // If non-null, add a note to the warning pointing back to the constructor.
2145 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002146 public:
2147 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002148 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002149 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002150 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002151 : Inherited(S.Context), S(S), Decls(Decls),
2152 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002153
Richard Trieufd687772013-09-16 20:46:50 +00002154 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002155 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2156 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002157
Richard Trieu1bc22c12013-09-13 03:20:53 +00002158 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2159 // or union.
2160 MemberExpr *FieldME = ME;
2161
2162 Expr *Base = ME;
2163 while (isa<MemberExpr>(Base)) {
2164 ME = cast<MemberExpr>(Base);
2165
2166 if (isa<VarDecl>(ME->getMemberDecl()))
2167 return;
2168
2169 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2170 if (!FD->isAnonymousStructOrUnion())
2171 FieldME = ME;
2172
2173 Base = ME->getBase();
2174 }
2175
Richard Trieufd687772013-09-16 20:46:50 +00002176 if (!isa<CXXThisExpr>(Base))
2177 return;
2178
Richard Trieu406e65c2013-09-20 03:03:06 +00002179 ValueDecl* FoundVD = FieldME->getMemberDecl();
2180
Richard Trieuef64e942013-10-25 00:56:00 +00002181 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002182 return;
2183
Richard Trieuef64e942013-10-25 00:56:00 +00002184 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002185
Richard Trieuef64e942013-10-25 00:56:00 +00002186 // Prevent double warnings on use of unbounded references.
2187 if (IsReference != CheckReferenceOnly)
2188 return;
2189
2190 unsigned diag = IsReference
2191 ? diag::warn_reference_field_is_uninit
2192 : diag::warn_field_is_uninit;
2193 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2194 if (Constructor)
2195 S.Diag(Constructor->getLocation(),
2196 diag::note_uninit_in_this_constructor)
2197 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2198
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002199 }
2200
2201 void HandleValue(Expr *E) {
2202 E = E->IgnoreParens();
2203
2204 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002205 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002206 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002207 }
2208
2209 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2210 HandleValue(CO->getTrueExpr());
2211 HandleValue(CO->getFalseExpr());
2212 return;
2213 }
2214
2215 if (BinaryConditionalOperator *BCO =
2216 dyn_cast<BinaryConditionalOperator>(E)) {
2217 HandleValue(BCO->getCommon());
2218 HandleValue(BCO->getFalseExpr());
2219 return;
2220 }
2221
2222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2223 switch (BO->getOpcode()) {
2224 default:
2225 return;
2226 case(BO_PtrMemD):
2227 case(BO_PtrMemI):
2228 HandleValue(BO->getLHS());
2229 return;
2230 case(BO_Comma):
2231 HandleValue(BO->getRHS());
2232 return;
2233 }
2234 }
2235 }
2236
Richard Trieu1bc22c12013-09-13 03:20:53 +00002237 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002238 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002240
2241 Inherited::VisitMemberExpr(ME);
2242 }
2243
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002244 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2245 if (E->getCastKind() == CK_LValueToRValue)
2246 HandleValue(E->getSubExpr());
2247
2248 Inherited::VisitImplicitCastExpr(E);
2249 }
2250
Richard Trieu1bc22c12013-09-13 03:20:53 +00002251 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002252 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2254 if (ICE->getCastKind() == CK_NoOp)
2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002257
2258 Inherited::VisitCXXConstructExpr(E);
2259 }
2260
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2262 Expr *Callee = E->getCallee();
2263 if (isa<MemberExpr>(Callee))
2264 HandleValue(Callee);
2265
2266 Inherited::VisitCXXMemberCallExpr(E);
2267 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002268
2269 void VisitBinaryOperator(BinaryOperator *E) {
2270 // If a field assignment is detected, remove the field from the
2271 // uninitiailized field set.
2272 if (E->getOpcode() == BO_Assign)
2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002275 if (!FD->getType()->isReferenceType())
2276 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002277
2278 Inherited::VisitBinaryOperator(E);
2279 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002280 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002281 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002282 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2283 const CXXConstructorDecl *Constructor) {
2284 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002285 return;
2286
Richard Trieuef64e942013-10-25 00:56:00 +00002287 if (!E)
2288 return;
2289
2290 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2291 E = Default->getExpr();
2292 if (!E)
2293 return;
2294 // In class initializers will point to the constructor.
2295 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2296 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002297 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
Richard Trieuef64e942013-10-25 00:56:00 +00002298 }
2299 }
2300
2301 // Diagnose value-uses of fields to initialize themselves, e.g.
2302 // foo(foo)
2303 // where foo is not also a parameter to the constructor.
2304 // Also diagnose across field uninitialized use such as
2305 // x(y), y(x)
2306 // TODO: implement -Wuninitialized and fold this into that framework.
2307 static void DiagnoseUninitializedFields(
2308 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2309
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002310 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2311 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002312 return;
2313 }
2314
2315 if (Constructor->isInvalidDecl())
2316 return;
2317
2318 const CXXRecordDecl *RD = Constructor->getParent();
2319
2320 // Holds fields that are uninitialized.
2321 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2322
2323 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002324 for (auto *I : RD->decls()) {
2325 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002326 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002327 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002328 UninitializedFields.insert(IFD->getAnonField());
2329 }
2330 }
2331
Aaron Ballman0ad78302014-03-13 17:34:31 +00002332 for (const auto *FieldInit : Constructor->inits()) {
2333 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002334
2335 CheckInitExprContainsUninitializedFields(
2336 SemaRef, InitExpr, UninitializedFields, Constructor);
2337
Aaron Ballman0ad78302014-03-13 17:34:31 +00002338 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002339 UninitializedFields.erase(Field);
2340 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002341 }
2342} // namespace
2343
Richard Smith74108172014-01-17 03:11:34 +00002344/// \brief Enter a new C++ default initializer scope. After calling this, the
2345/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2346/// parsing or instantiating the initializer failed.
2347void Sema::ActOnStartCXXInClassMemberInitializer() {
2348 // Create a synthetic function scope to represent the call to the constructor
2349 // that notionally surrounds a use of this initializer.
2350 PushFunctionScope();
2351}
2352
2353/// \brief This is invoked after parsing an in-class initializer for a
2354/// non-static C++ class member, and after instantiating an in-class initializer
2355/// in a class template. Such actions are deferred until the class is complete.
2356void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2357 SourceLocation InitLoc,
2358 Expr *InitExpr) {
2359 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002360 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002361
Richard Smith938f40b2011-06-11 17:19:42 +00002362 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002363 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2364 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002365
2366 if (!InitExpr) {
2367 FD->setInvalidDecl();
2368 FD->removeInClassInitializer();
2369 return;
2370 }
2371
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002372 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2373 FD->setInvalidDecl();
2374 FD->removeInClassInitializer();
2375 return;
2376 }
2377
Richard Smith938f40b2011-06-11 17:19:42 +00002378 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002379 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002380 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002381 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002382 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002383 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002384 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2385 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002386 if (Init.isInvalid()) {
2387 FD->setInvalidDecl();
2388 return;
2389 }
Richard Smith938f40b2011-06-11 17:19:42 +00002390 }
2391
Richard Smith945f8d32013-01-14 22:39:08 +00002392 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002393 // The initialization of each base and member constitutes a
2394 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002395 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002396 if (Init.isInvalid()) {
2397 FD->setInvalidDecl();
2398 return;
2399 }
2400
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002401 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002402
2403 FD->setInClassInitializer(InitExpr);
2404}
2405
Douglas Gregor15e77a22009-12-31 09:10:24 +00002406/// \brief Find the direct and/or virtual base specifiers that
2407/// correspond to the given base type, for use in base initialization
2408/// within a constructor.
2409static bool FindBaseInitializer(Sema &SemaRef,
2410 CXXRecordDecl *ClassDecl,
2411 QualType BaseType,
2412 const CXXBaseSpecifier *&DirectBaseSpec,
2413 const CXXBaseSpecifier *&VirtualBaseSpec) {
2414 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002415 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002416 for (const auto &Base : ClassDecl->bases()) {
2417 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002418 // We found a direct base of this type. That's what we're
2419 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002420 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002421 break;
2422 }
2423 }
2424
2425 // Check for a virtual base class.
2426 // FIXME: We might be able to short-circuit this if we know in advance that
2427 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002428 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002429 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2430 // We haven't found a base yet; search the class hierarchy for a
2431 // virtual base class.
2432 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2433 /*DetectVirtual=*/false);
2434 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2435 BaseType, Paths)) {
2436 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2437 Path != Paths.end(); ++Path) {
2438 if (Path->back().Base->isVirtual()) {
2439 VirtualBaseSpec = Path->back().Base;
2440 break;
2441 }
2442 }
2443 }
2444 }
2445
2446 return DirectBaseSpec || VirtualBaseSpec;
2447}
2448
Sebastian Redla74948d2011-09-24 17:48:25 +00002449/// \brief Handle a C++ member initializer using braced-init-list syntax.
2450MemInitResult
2451Sema::ActOnMemInitializer(Decl *ConstructorD,
2452 Scope *S,
2453 CXXScopeSpec &SS,
2454 IdentifierInfo *MemberOrBase,
2455 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002456 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002457 SourceLocation IdLoc,
2458 Expr *InitList,
2459 SourceLocation EllipsisLoc) {
2460 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002461 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002462 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002463}
2464
2465/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002466MemInitResult
John McCall48871652010-08-21 09:40:31 +00002467Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002468 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002469 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002470 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002471 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002472 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002473 SourceLocation IdLoc,
2474 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002475 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002476 SourceLocation RParenLoc,
2477 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002478 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002479 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002480 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002481 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002482}
2483
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002484namespace {
2485
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002486// Callback to only accept typo corrections that can be a valid C++ member
2487// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002488class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002489public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002490 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2491 : ClassDecl(ClassDecl) {}
2492
Craig Toppera798a9d2014-03-02 09:32:10 +00002493 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002494 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2495 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2496 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002497 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002498 }
2499 return false;
2500 }
2501
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002502private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002503 CXXRecordDecl *ClassDecl;
2504};
2505
2506}
2507
Sebastian Redla74948d2011-09-24 17:48:25 +00002508/// \brief Handle a C++ member initializer.
2509MemInitResult
2510Sema::BuildMemInitializer(Decl *ConstructorD,
2511 Scope *S,
2512 CXXScopeSpec &SS,
2513 IdentifierInfo *MemberOrBase,
2514 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002515 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002516 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002517 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002518 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002519 if (!ConstructorD)
2520 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002522 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002523
2524 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002525 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002526 if (!Constructor) {
2527 // The user wrote a constructor initializer on a function that is
2528 // not a C++ constructor. Ignore the error for now, because we may
2529 // have more member initializers coming; we'll diagnose it just
2530 // once in ActOnMemInitializers.
2531 return true;
2532 }
2533
2534 CXXRecordDecl *ClassDecl = Constructor->getParent();
2535
2536 // C++ [class.base.init]p2:
2537 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002538 // constructor's class and, if not found in that scope, are looked
2539 // up in the scope containing the constructor's definition.
2540 // [Note: if the constructor's class contains a member with the
2541 // same name as a direct or virtual base class of the class, a
2542 // mem-initializer-id naming the member or base class and composed
2543 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002544 // mem-initializer-id for the hidden base class may be specified
2545 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002546 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002547 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002548 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002549 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002550 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002551 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002552 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2553 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002554 if (EllipsisLoc.isValid())
2555 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002556 << MemberOrBase
2557 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002558
Sebastian Redla9351792012-02-11 23:51:47 +00002559 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002560 }
Francois Pichetd583da02010-12-04 09:14:42 +00002561 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002562 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002563 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002564 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002565 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002566
2567 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002568 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002569 } else if (DS.getTypeSpecType() == TST_decltype) {
2570 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002571 } else {
2572 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2573 LookupParsedName(R, S, &SS);
2574
2575 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2576 if (!TyD) {
2577 if (R.isAmbiguous()) return true;
2578
John McCallda6841b2010-04-09 19:01:14 +00002579 // We don't want access-control diagnostics here.
2580 R.suppressDiagnostics();
2581
Douglas Gregora3b624a2010-01-19 06:46:48 +00002582 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2583 bool NotUnknownSpecialization = false;
2584 DeclContext *DC = computeDeclContext(SS, false);
2585 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2586 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2587
2588 if (!NotUnknownSpecialization) {
2589 // When the scope specifier can refer to a member of an unknown
2590 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002591 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2592 SS.getWithLocInContext(Context),
2593 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002594 if (BaseType.isNull())
2595 return true;
2596
Douglas Gregora3b624a2010-01-19 06:46:48 +00002597 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002598 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002599 }
2600 }
2601
Douglas Gregor15e77a22009-12-31 09:10:24 +00002602 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002603 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002604 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002605 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002606 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002607 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002608 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002609 // We have found a non-static data member with a similar
2610 // name to what was typed; complain and initialize that
2611 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002612 diagnoseTypo(Corr,
2613 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2614 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002615 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002616 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002617 const CXXBaseSpecifier *DirectBaseSpec;
2618 const CXXBaseSpecifier *VirtualBaseSpec;
2619 if (FindBaseInitializer(*this, ClassDecl,
2620 Context.getTypeDeclType(Type),
2621 DirectBaseSpec, VirtualBaseSpec)) {
2622 // We have found a direct or virtual base class with a
2623 // similar name to what was typed; complain and initialize
2624 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002625 diagnoseTypo(Corr,
2626 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2627 << MemberOrBase << false,
2628 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002629
Richard Smithf9b15102013-08-17 00:46:16 +00002630 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2631 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002632 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002633 diag::note_base_class_specified_here)
2634 << BaseSpec->getType()
2635 << BaseSpec->getSourceRange();
2636
Douglas Gregor15e77a22009-12-31 09:10:24 +00002637 TyD = Type;
2638 }
2639 }
2640 }
2641
Douglas Gregora3b624a2010-01-19 06:46:48 +00002642 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002643 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002644 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002645 return true;
2646 }
John McCallb5a0d312009-12-21 10:41:20 +00002647 }
2648
Douglas Gregora3b624a2010-01-19 06:46:48 +00002649 if (BaseType.isNull()) {
2650 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002651 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002652 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002653 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2654 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002655 }
2656 }
Mike Stump11289f42009-09-09 15:08:12 +00002657
John McCallbcd03502009-12-07 02:54:59 +00002658 if (!TInfo)
2659 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002660
Sebastian Redla9351792012-02-11 23:51:47 +00002661 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002662}
2663
Chandler Carruth599deef2011-09-03 01:14:15 +00002664/// Checks a member initializer expression for cases where reference (or
2665/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002666static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2667 Expr *Init,
2668 SourceLocation IdLoc) {
2669 QualType MemberTy = Member->getType();
2670
2671 // We only handle pointers and references currently.
2672 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2673 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2674 return;
2675
2676 const bool IsPointer = MemberTy->isPointerType();
2677 if (IsPointer) {
2678 if (const UnaryOperator *Op
2679 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2680 // The only case we're worried about with pointers requires taking the
2681 // address.
2682 if (Op->getOpcode() != UO_AddrOf)
2683 return;
2684
2685 Init = Op->getSubExpr();
2686 } else {
2687 // We only handle address-of expression initializers for pointers.
2688 return;
2689 }
2690 }
2691
Richard Smithe3b28bc2013-06-12 21:51:50 +00002692 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002693 // We only warn when referring to a non-reference parameter declaration.
2694 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2695 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002696 return;
2697
2698 S.Diag(Init->getExprLoc(),
2699 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2700 : diag::warn_bind_ref_member_to_parameter)
2701 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002702 } else {
2703 // Other initializers are fine.
2704 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002705 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002706
2707 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2708 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002709}
2710
John McCallfaf5fb42010-08-26 23:41:50 +00002711MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002712Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002713 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002714 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2715 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2716 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002717 "Member must be a FieldDecl or IndirectFieldDecl");
2718
Sebastian Redla9351792012-02-11 23:51:47 +00002719 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002720 return true;
2721
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002722 if (Member->isInvalidDecl())
2723 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002724
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002725 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002726 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002727 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002728 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002729 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002730 } else {
2731 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002732 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002733 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002734
Sebastian Redla9351792012-02-11 23:51:47 +00002735 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002736
Sebastian Redla9351792012-02-11 23:51:47 +00002737 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002738 // Can't check initialization for a member of dependent type or when
2739 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002740 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002741 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002742 bool InitList = false;
2743 if (isa<InitListExpr>(Init)) {
2744 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002745 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002746 }
2747
Chandler Carruthd44c3102010-12-06 09:23:57 +00002748 // Initialize the member.
2749 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00002750 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2751 : InitializedEntity::InitializeMember(IndirectMember,
2752 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002753 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002754 InitList ? InitializationKind::CreateDirectList(IdLoc)
2755 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2756 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002757
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002758 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002759 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2760 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002761 if (MemberInit.isInvalid())
2762 return true;
2763
Richard Smith736a9472013-06-12 20:42:33 +00002764 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2765
Richard Smith945f8d32013-01-14 22:39:08 +00002766 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002767 // The initialization of each base and member constitutes a
2768 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002769 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002770 if (MemberInit.isInvalid())
2771 return true;
2772
Richard Smithd59b8322012-12-19 01:39:02 +00002773 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002774 }
2775
Chandler Carruthd44c3102010-12-06 09:23:57 +00002776 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002777 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2778 InitRange.getBegin(), Init,
2779 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002780 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002781 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2782 InitRange.getBegin(), Init,
2783 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002784 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002785}
2786
John McCallfaf5fb42010-08-26 23:41:50 +00002787MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002788Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002789 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002790 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002791 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002792 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002793 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002794 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002795
Sebastian Redl0501c632012-02-12 16:37:36 +00002796 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002797 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002798 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2799 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002800 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002801 }
2802
Sebastian Redla9351792012-02-11 23:51:47 +00002803 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002804 // Initialize the object.
2805 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2806 QualType(ClassDecl->getTypeForDecl(), 0));
2807 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002808 InitList ? InitializationKind::CreateDirectList(NameLoc)
2809 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2810 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002811 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002812 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00002813 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002814 if (DelegationInit.isInvalid())
2815 return true;
2816
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002817 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2818 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002819
Richard Smith945f8d32013-01-14 22:39:08 +00002820 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002821 // The initialization of each base and member constitutes a
2822 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002823 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2824 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002825 if (DelegationInit.isInvalid())
2826 return true;
2827
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002828 // If we are in a dependent context, template instantiation will
2829 // perform this type-checking again. Just save the arguments that we
2830 // received in a ParenListExpr.
2831 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2832 // of the information that we have about the base
2833 // initializer. However, deconstructing the ASTs is a dicey process,
2834 // and this approach is far more likely to get the corner cases right.
2835 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002836 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002837
Sebastian Redla9351792012-02-11 23:51:47 +00002838 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002839 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002840 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002841}
2842
2843MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002844Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002845 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002846 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002847 SourceLocation BaseLoc
2848 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002849
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002850 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2851 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2852 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2853
2854 // C++ [class.base.init]p2:
2855 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002856 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002857 // of that class, the mem-initializer is ill-formed. A
2858 // mem-initializer-list can initialize a base class using any
2859 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002860 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002861
Sebastian Redla9351792012-02-11 23:51:47 +00002862 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002863 if (EllipsisLoc.isValid()) {
2864 // This is a pack expansion.
2865 if (!BaseType->containsUnexpandedParameterPack()) {
2866 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002867 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002868
Douglas Gregor44e7df62011-01-04 00:32:56 +00002869 EllipsisLoc = SourceLocation();
2870 }
2871 } else {
2872 // Check for any unexpanded parameter packs.
2873 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2874 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002875
Sebastian Redla9351792012-02-11 23:51:47 +00002876 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002877 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002878 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002879
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002880 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00002881 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2882 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002883 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002884 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2885 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002886 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002887
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002888 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2889 VirtualBaseSpec);
2890
2891 // C++ [base.class.init]p2:
2892 // Unless the mem-initializer-id names a nonstatic data member of the
2893 // constructor's class or a direct or virtual base of that class, the
2894 // mem-initializer is ill-formed.
2895 if (!DirectBaseSpec && !VirtualBaseSpec) {
2896 // If the class has any dependent bases, then it's possible that
2897 // one of those types will resolve to the same type as
2898 // BaseType. Therefore, just treat this as a dependent base
2899 // class initialization. FIXME: Should we try to check the
2900 // initialization anyway? It seems odd.
2901 if (ClassDecl->hasAnyDependentBases())
2902 Dependent = true;
2903 else
2904 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2905 << BaseType << Context.getTypeDeclType(ClassDecl)
2906 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2907 }
2908 }
2909
2910 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002911 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002912
Sebastian Redla74948d2011-09-24 17:48:25 +00002913 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2914 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002915 InitRange.getBegin(), Init,
2916 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002917 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002918
2919 // C++ [base.class.init]p2:
2920 // If a mem-initializer-id is ambiguous because it designates both
2921 // a direct non-virtual base class and an inherited virtual base
2922 // class, the mem-initializer is ill-formed.
2923 if (DirectBaseSpec && VirtualBaseSpec)
2924 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002925 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002926
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002927 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002928 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002929 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002930
2931 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002932 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002933 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002934 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002935 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002936 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002937 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002938
2939 InitializedEntity BaseEntity =
2940 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2941 InitializationKind Kind =
2942 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2943 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2944 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002945 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002946 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002947 if (BaseInit.isInvalid())
2948 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002949
Richard Smith945f8d32013-01-14 22:39:08 +00002950 // C++11 [class.base.init]p7:
2951 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002952 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002953 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002954 if (BaseInit.isInvalid())
2955 return true;
2956
2957 // If we are in a dependent context, template instantiation will
2958 // perform this type-checking again. Just save the arguments that we
2959 // received in a ParenListExpr.
2960 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2961 // of the information that we have about the base
2962 // initializer. However, deconstructing the ASTs is a dicey process,
2963 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002964 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002965 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002966
Alexis Hunt1d792652011-01-08 20:30:50 +00002967 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002968 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002969 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002970 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002971 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002972}
2973
Sebastian Redl22653ba2011-08-30 19:58:05 +00002974// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002975static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2976 if (T.isNull()) T = E->getType();
2977 QualType TargetType = SemaRef.BuildReferenceType(
2978 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002979 SourceLocation ExprLoc = E->getLocStart();
2980 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2981 TargetType, ExprLoc);
2982
2983 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2984 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002985 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002986}
2987
Anders Carlsson1b00e242010-04-23 03:10:23 +00002988/// ImplicitInitializerKind - How an implicit base or member initializer should
2989/// initialize its base or member.
2990enum ImplicitInitializerKind {
2991 IIK_Default,
2992 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002993 IIK_Move,
2994 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002995};
2996
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002997static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002998BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002999 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003000 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003001 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003002 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003003 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003004 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3005 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003006
John McCalldadc5752010-08-24 06:29:42 +00003007 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003008
3009 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003010 case IIK_Inherit: {
3011 const CXXRecordDecl *Inherited =
3012 Constructor->getInheritedConstructor()->getParent();
3013 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3014 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3015 // C++11 [class.inhctor]p8:
3016 // Each expression in the expression-list is of the form
3017 // static_cast<T&&>(p), where p is the name of the corresponding
3018 // constructor parameter and T is the declared type of p.
3019 SmallVector<Expr*, 16> Args;
3020 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3021 ParmVarDecl *PD = Constructor->getParamDecl(I);
3022 ExprResult ArgExpr =
3023 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3024 VK_LValue, SourceLocation());
3025 if (ArgExpr.isInvalid())
3026 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003027 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003028 }
3029
3030 InitializationKind InitKind = InitializationKind::CreateDirect(
3031 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003032 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003033 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3034 break;
3035 }
3036 }
3037 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003038 case IIK_Default: {
3039 InitializationKind InitKind
3040 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003041 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3042 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003043 break;
3044 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003045
Sebastian Redl22653ba2011-08-30 19:58:05 +00003046 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003047 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003048 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003049 ParmVarDecl *Param = Constructor->getParamDecl(0);
3050 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003051
Anders Carlsson1b00e242010-04-23 03:10:23 +00003052 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003053 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003054 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003055 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003056 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003057
Eli Friedmanfa0df832012-02-02 03:46:19 +00003058 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3059
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003060 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003061 QualType ArgTy =
3062 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3063 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003064
Sebastian Redl22653ba2011-08-30 19:58:05 +00003065 if (Moving) {
3066 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3067 }
3068
John McCallcf142162010-08-07 06:22:56 +00003069 CXXCastPath BasePath;
3070 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003071 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3072 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003073 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003074 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003075
Anders Carlsson1b00e242010-04-23 03:10:23 +00003076 InitializationKind InitKind
3077 = InitializationKind::CreateDirect(Constructor->getLocation(),
3078 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003079 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3080 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003081 break;
3082 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003083 }
John McCallb268a282010-08-23 23:25:46 +00003084
Douglas Gregora40433a2010-12-07 00:41:46 +00003085 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003086 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003087 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003088
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003089 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003090 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003091 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3092 SourceLocation()),
3093 BaseSpec->isVirtual(),
3094 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003095 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003096 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003097 SourceLocation());
3098
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003099 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003100}
3101
Sebastian Redl22653ba2011-08-30 19:58:05 +00003102static bool RefersToRValueRef(Expr *MemRef) {
3103 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3104 return Referenced->getType()->isRValueReferenceType();
3105}
3106
Anders Carlsson3c1db572010-04-23 02:15:47 +00003107static bool
3108BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003109 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003110 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003111 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003112 if (Field->isInvalidDecl())
3113 return true;
3114
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003115 SourceLocation Loc = Constructor->getLocation();
3116
Sebastian Redl22653ba2011-08-30 19:58:05 +00003117 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3118 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003119 ParmVarDecl *Param = Constructor->getParamDecl(0);
3120 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003121
3122 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003123 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3124 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003125
Anders Carlsson423f5d82010-04-23 16:04:08 +00003126 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003127 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003128 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003129 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003130
Eli Friedmanfa0df832012-02-02 03:46:19 +00003131 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3132
Sebastian Redl22653ba2011-08-30 19:58:05 +00003133 if (Moving) {
3134 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3135 }
3136
Douglas Gregor94f9a482010-05-05 05:51:00 +00003137 // Build a reference to this field within the parameter.
3138 CXXScopeSpec SS;
3139 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3140 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003141 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3142 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003143 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003144 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003145 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003146 ParamType, Loc,
3147 /*IsArrow=*/false,
3148 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003149 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003150 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003151 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003152 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003153 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003154 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003155
3156 // C++11 [class.copy]p15:
3157 // - if a member m has rvalue reference type T&&, it is direct-initialized
3158 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003159 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003160 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003161 }
3162
Douglas Gregor94f9a482010-05-05 05:51:00 +00003163 // When the field we are copying is an array, create index variables for
3164 // each dimension of the array. We use these index variables to subscript
3165 // the source array, and other clients (e.g., CodeGen) will perform the
3166 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003167 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003168 QualType BaseType = Field->getType();
3169 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003170 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003171 while (const ConstantArrayType *Array
3172 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003173 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003174 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003175 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003176 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003177 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003178 llvm::raw_svector_ostream OS(Str);
3179 OS << "__i" << IndexVariables.size();
3180 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3181 }
3182 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003183 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003184 IterationVarName, SizeType,
3185 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003186 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003187 IndexVariables.push_back(IterationVar);
3188
3189 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003190 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003191 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003192 assert(!IterationVarRef.isInvalid() &&
3193 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003194 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003195 assert(!IterationVarRef.isInvalid() &&
3196 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003197
Douglas Gregor94f9a482010-05-05 05:51:00 +00003198 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003199 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3200 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003201 Loc);
3202 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003203 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003204
Douglas Gregor94f9a482010-05-05 05:51:00 +00003205 BaseType = Array->getElementType();
3206 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003207
3208 // The array subscript expression is an lvalue, which is wrong for moving.
3209 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003210 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003211
Douglas Gregor94f9a482010-05-05 05:51:00 +00003212 // Construct the entity that we will be initializing. For an array, this
3213 // will be first element in the array, which may require several levels
3214 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003215 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003216 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003217 if (Indirect)
3218 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3219 else
3220 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003221 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3222 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3223 0,
3224 Entities.back()));
3225
3226 // Direct-initialize to use the copy constructor.
3227 InitializationKind InitKind =
3228 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3229
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003230 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003231 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003232
John McCalldadc5752010-08-24 06:29:42 +00003233 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003234 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003235 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003236 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003237 if (MemberInit.isInvalid())
3238 return true;
3239
Douglas Gregor493627b2011-08-10 15:22:55 +00003240 if (Indirect) {
3241 assert(IndexVariables.size() == 0 &&
3242 "Indirect field improperly initialized");
3243 CXXMemberInit
3244 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3245 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003246 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003247 Loc);
3248 } else
3249 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003250 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003251 Loc,
3252 IndexVariables.data(),
3253 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003254 return false;
3255 }
3256
Richard Smithc2bc61b2013-03-18 21:12:30 +00003257 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3258 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003259
Anders Carlsson3c1db572010-04-23 02:15:47 +00003260 QualType FieldBaseElementType =
3261 SemaRef.Context.getBaseElementType(Field->getType());
3262
Anders Carlsson3c1db572010-04-23 02:15:47 +00003263 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003264 InitializedEntity InitEntity
3265 = Indirect? InitializedEntity::InitializeMember(Indirect)
3266 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003267 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003268 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003269
3270 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3271 ExprResult MemberInit =
3272 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003273
Douglas Gregora40433a2010-12-07 00:41:46 +00003274 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003275 if (MemberInit.isInvalid())
3276 return true;
3277
Douglas Gregor493627b2011-08-10 15:22:55 +00003278 if (Indirect)
3279 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3280 Indirect, Loc,
3281 Loc,
3282 MemberInit.get(),
3283 Loc);
3284 else
3285 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3286 Field, Loc, Loc,
3287 MemberInit.get(),
3288 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003289 return false;
3290 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003291
Alexis Hunt8b455182011-05-17 00:19:05 +00003292 if (!Field->getParent()->isUnion()) {
3293 if (FieldBaseElementType->isReferenceType()) {
3294 SemaRef.Diag(Constructor->getLocation(),
3295 diag::err_uninitialized_member_in_ctor)
3296 << (int)Constructor->isImplicit()
3297 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3298 << 0 << Field->getDeclName();
3299 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3300 return true;
3301 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003302
Alexis Hunt8b455182011-05-17 00:19:05 +00003303 if (FieldBaseElementType.isConstQualified()) {
3304 SemaRef.Diag(Constructor->getLocation(),
3305 diag::err_uninitialized_member_in_ctor)
3306 << (int)Constructor->isImplicit()
3307 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3308 << 1 << Field->getDeclName();
3309 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3310 return true;
3311 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003312 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003313
David Blaikiebbafb8a2012-03-11 07:00:24 +00003314 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003315 FieldBaseElementType->isObjCRetainableType() &&
3316 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3317 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003318 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003319 // Default-initialize Objective-C pointers to NULL.
3320 CXXMemberInit
3321 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3322 Loc, Loc,
3323 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3324 Loc);
3325 return false;
3326 }
3327
Anders Carlsson3c1db572010-04-23 02:15:47 +00003328 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003329 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003330 return false;
3331}
John McCallbc83b3f2010-05-20 23:23:51 +00003332
3333namespace {
3334struct BaseAndFieldInfo {
3335 Sema &S;
3336 CXXConstructorDecl *Ctor;
3337 bool AnyErrorsInInits;
3338 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003339 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003340 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003341 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003342
3343 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3344 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003345 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3346 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003347 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003348 else if (Generated && Ctor->isMoveConstructor())
3349 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003350 else if (Ctor->getInheritedConstructor())
3351 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003352 else
3353 IIK = IIK_Default;
3354 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003355
3356 bool isImplicitCopyOrMove() const {
3357 switch (IIK) {
3358 case IIK_Copy:
3359 case IIK_Move:
3360 return true;
3361
3362 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003363 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003364 return false;
3365 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003366
3367 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003368 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003369
3370 bool addFieldInitializer(CXXCtorInitializer *Init) {
3371 AllToInit.push_back(Init);
3372
3373 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003374 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003375 S.UnusedPrivateFields.remove(Init->getAnyMember());
3376
3377 return false;
3378 }
John McCallbc83b3f2010-05-20 23:23:51 +00003379
Richard Smithab44d5b2013-12-10 08:25:00 +00003380 bool isInactiveUnionMember(FieldDecl *Field) {
3381 RecordDecl *Record = Field->getParent();
3382 if (!Record->isUnion())
3383 return false;
3384
Richard Smith8d183852013-12-10 20:56:03 +00003385 if (FieldDecl *Active =
3386 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003387 return Active != Field->getCanonicalDecl();
3388
3389 // In an implicit copy or move constructor, ignore any in-class initializer.
3390 if (isImplicitCopyOrMove())
3391 return true;
3392
3393 // If there's no explicit initialization, the field is active only if it
3394 // has an in-class initializer...
3395 if (Field->hasInClassInitializer())
3396 return false;
3397 // ... or it's an anonymous struct or union whose class has an in-class
3398 // initializer.
3399 if (!Field->isAnonymousStructOrUnion())
3400 return true;
3401 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3402 return !FieldRD->hasInClassInitializer();
3403 }
3404
3405 /// \brief Determine whether the given field is, or is within, a union member
3406 /// that is inactive (because there was an initializer given for a different
3407 /// member of the union, or because the union was not initialized at all).
3408 bool isWithinInactiveUnionMember(FieldDecl *Field,
3409 IndirectFieldDecl *Indirect) {
3410 if (!Indirect)
3411 return isInactiveUnionMember(Field);
3412
Aaron Ballman29c94602014-03-07 18:36:15 +00003413 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003414 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003415 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003416 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003417 }
3418 return false;
3419 }
3420};
Richard Smithc94ec842011-09-19 13:34:43 +00003421}
3422
Douglas Gregor10f939c2011-11-02 23:04:16 +00003423/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3424/// array type.
3425static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3426 if (T->isIncompleteArrayType())
3427 return true;
3428
3429 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3430 if (!ArrayT->getSize())
3431 return true;
3432
3433 T = ArrayT->getElementType();
3434 }
3435
3436 return false;
3437}
3438
Richard Smith938f40b2011-06-11 17:19:42 +00003439static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003440 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003441 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003442 if (Field->isInvalidDecl())
3443 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003444
Chandler Carruth139e9622010-06-30 02:59:29 +00003445 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003446 if (CXXCtorInitializer *Init =
3447 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003448 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003449
Richard Smithab44d5b2013-12-10 08:25:00 +00003450 // C++11 [class.base.init]p8:
3451 // if the entity is a non-static data member that has a
3452 // brace-or-equal-initializer and either
3453 // -- the constructor's class is a union and no other variant member of that
3454 // union is designated by a mem-initializer-id or
3455 // -- the constructor's class is not a union, and, if the entity is a member
3456 // of an anonymous union, no other member of that union is designated by
3457 // a mem-initializer-id,
3458 // the entity is initialized as specified in [dcl.init].
3459 //
3460 // We also apply the same rules to handle anonymous structs within anonymous
3461 // unions.
3462 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3463 return false;
3464
Douglas Gregor7db3e952011-11-28 20:03:15 +00003465 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003466 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3467 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003468 CXXCtorInitializer *Init;
3469 if (Indirect)
3470 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3471 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003472 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003473 SourceLocation());
3474 else
3475 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3476 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003477 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003478 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003479 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003480 }
3481
Douglas Gregor10f939c2011-11-02 23:04:16 +00003482 // Don't initialize incomplete or zero-length arrays.
3483 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3484 return false;
3485
John McCallbc83b3f2010-05-20 23:23:51 +00003486 // Don't try to build an implicit initializer if there were semantic
3487 // errors in any of the initializers (and therefore we might be
3488 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003489 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003490 return false;
3491
Craig Topperc3ec1492014-05-26 06:22:03 +00003492 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003493 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3494 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003495 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003496
Richard Smith0a8cfc72012-08-07 21:30:42 +00003497 if (!Init)
3498 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003499
Richard Smith0a8cfc72012-08-07 21:30:42 +00003500 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003501}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003502
3503bool
3504Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3505 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003506 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003507 Constructor->setNumCtorInitializers(1);
3508 CXXCtorInitializer **initializer =
3509 new (Context) CXXCtorInitializer*[1];
3510 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3511 Constructor->setCtorInitializers(initializer);
3512
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003513 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003514 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003515 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3516 }
3517
Alexis Hunte2622992011-05-05 00:05:47 +00003518 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003519
Alexis Hunt61bc1732011-05-01 07:04:31 +00003520 return false;
3521}
Douglas Gregor493627b2011-08-10 15:22:55 +00003522
David Blaikie3fc2f912013-01-17 05:26:25 +00003523bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3524 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003525 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003526 // Just store the initializers as written, they will be checked during
3527 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003528 if (!Initializers.empty()) {
3529 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003530 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003531 new (Context) CXXCtorInitializer*[Initializers.size()];
3532 memcpy(baseOrMemberInitializers, Initializers.data(),
3533 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003534 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003535 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003536
3537 // Let template instantiation know whether we had errors.
3538 if (AnyErrors)
3539 Constructor->setInvalidDecl();
3540
Anders Carlssondb0a9652010-04-02 06:26:44 +00003541 return false;
3542 }
3543
John McCallbc83b3f2010-05-20 23:23:51 +00003544 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003545
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003546 // We need to build the initializer AST according to order of construction
3547 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003548 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003549 if (!ClassDecl)
3550 return true;
3551
Eli Friedman9cf6b592009-11-09 19:20:36 +00003552 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003553
David Blaikie3fc2f912013-01-17 05:26:25 +00003554 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003555 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003556
Anders Carlssondb0a9652010-04-02 06:26:44 +00003557 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003558 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003559 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003560 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003561
3562 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003563 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003564 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003565 if (FD && FD->getParent()->isUnion())
3566 Info.ActiveUnionMember.insert(std::make_pair(
3567 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3568 }
3569 } else if (FieldDecl *FD = Member->getMember()) {
3570 if (FD->getParent()->isUnion())
3571 Info.ActiveUnionMember.insert(std::make_pair(
3572 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3573 }
3574 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003575 }
3576
Anders Carlsson43c64af2010-04-21 19:52:01 +00003577 // Keep track of the direct virtual bases.
3578 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003579 for (auto &I : ClassDecl->bases()) {
3580 if (I.isVirtual())
3581 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003582 }
3583
Anders Carlssondb0a9652010-04-02 06:26:44 +00003584 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003585 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003586 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003587 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003588 // [class.base.init]p7, per DR257:
3589 // A mem-initializer where the mem-initializer-id names a virtual base
3590 // class is ignored during execution of a constructor of any class that
3591 // is not the most derived class.
3592 if (ClassDecl->isAbstract()) {
3593 // FIXME: Provide a fixit to remove the base specifier. This requires
3594 // tracking the location of the associated comma for a base specifier.
3595 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003596 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003597 DiagnoseAbstractType(ClassDecl);
3598 }
3599
John McCallbc83b3f2010-05-20 23:23:51 +00003600 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003601 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3602 // [class.base.init]p8, per DR257:
3603 // If a given [...] base class is not named by a mem-initializer-id
3604 // [...] and the entity is not a virtual base class of an abstract
3605 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003606 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003607 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003608 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003609 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003610 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003611 HadError = true;
3612 continue;
3613 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003614
John McCallbc83b3f2010-05-20 23:23:51 +00003615 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003616 }
3617 }
Mike Stump11289f42009-09-09 15:08:12 +00003618
John McCallbc83b3f2010-05-20 23:23:51 +00003619 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003620 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003621 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003622 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003623 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003624
Alexis Hunt1d792652011-01-08 20:30:50 +00003625 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003626 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003627 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003628 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003629 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003630 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003631 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003632 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003633 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003634 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003635 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003636
John McCallbc83b3f2010-05-20 23:23:51 +00003637 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003638 }
3639 }
Mike Stump11289f42009-09-09 15:08:12 +00003640
John McCallbc83b3f2010-05-20 23:23:51 +00003641 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003642 for (auto *Mem : ClassDecl->decls()) {
3643 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003644 // C++ [class.bit]p2:
3645 // A declaration for a bit-field that omits the identifier declares an
3646 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3647 // initialized.
3648 if (F->isUnnamedBitfield())
3649 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003650
Sebastian Redl22653ba2011-08-30 19:58:05 +00003651 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003652 // handle anonymous struct/union fields based on their individual
3653 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003654 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003655 continue;
3656
3657 if (CollectFieldInitializer(*this, Info, F))
3658 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003659 continue;
3660 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003661
3662 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003663 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003664 continue;
3665
Aaron Ballman629afae2014-03-07 19:56:05 +00003666 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003667 if (F->getType()->isIncompleteArrayType()) {
3668 assert(ClassDecl->hasFlexibleArrayMember() &&
3669 "Incomplete array type is not valid");
3670 continue;
3671 }
3672
Douglas Gregor493627b2011-08-10 15:22:55 +00003673 // Initialize each field of an anonymous struct individually.
3674 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3675 HadError = true;
3676
3677 continue;
3678 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
David Blaikie3fc2f912013-01-17 05:26:25 +00003681 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003682 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003683 Constructor->setNumCtorInitializers(NumInitializers);
3684 CXXCtorInitializer **baseOrMemberInitializers =
3685 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003686 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003687 NumInitializers * sizeof(CXXCtorInitializer*));
3688 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003689
John McCalla6309952010-03-16 21:39:52 +00003690 // Constructors implicitly reference the base and member
3691 // destructors.
3692 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3693 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003694 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003695
3696 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003697}
3698
David Blaikieb61b8152013-01-17 08:49:22 +00003699static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003700 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003701 const RecordDecl *RD = RT->getDecl();
3702 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003703 for (auto *Field : RD->fields())
3704 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003705 return;
3706 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003707 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003708 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003709}
3710
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003711static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3712 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003713}
3714
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003715static const void *GetKeyForMember(ASTContext &Context,
3716 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003717 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003718 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003719
Richard Smithcd45dbc2014-04-19 03:48:30 +00003720 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003721}
3722
David Blaikie3fc2f912013-01-17 05:26:25 +00003723static void DiagnoseBaseOrMemInitializerOrder(
3724 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3725 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003726 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003727 return;
Mike Stump11289f42009-09-09 15:08:12 +00003728
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003729 // Don't check initializers order unless the warning is enabled at the
3730 // location of at least one initializer.
3731 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003732 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003733 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003734 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3735 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003736 ShouldCheckOrder = true;
3737 break;
3738 }
3739 }
3740 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003741 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003742
John McCallbb7b6582010-04-10 07:37:23 +00003743 // Build the list of bases and members in the order that they'll
3744 // actually be initialized. The explicit initializers should be in
3745 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003746 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003747
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003748 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3749
John McCallbb7b6582010-04-10 07:37:23 +00003750 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003751 for (const auto &VBase : ClassDecl->vbases())
3752 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003753
John McCallbb7b6582010-04-10 07:37:23 +00003754 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003755 for (const auto &Base : ClassDecl->bases()) {
3756 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003757 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003758 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003759 }
Mike Stump11289f42009-09-09 15:08:12 +00003760
John McCallbb7b6582010-04-10 07:37:23 +00003761 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003762 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003763 if (Field->isUnnamedBitfield())
3764 continue;
3765
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003766 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003767 }
3768
John McCallbb7b6582010-04-10 07:37:23 +00003769 unsigned NumIdealInits = IdealInitKeys.size();
3770 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003771
Craig Topperc3ec1492014-05-26 06:22:03 +00003772 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00003773 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003774 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003775 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003776
3777 // Scan forward to try to find this initializer in the idealized
3778 // initializers list.
3779 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3780 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003781 break;
John McCallbb7b6582010-04-10 07:37:23 +00003782
3783 // If we didn't find this initializer, it must be because we
3784 // scanned past it on a previous iteration. That can only
3785 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003786 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003787 Sema::SemaDiagnosticBuilder D =
3788 SemaRef.Diag(PrevInit->getSourceLocation(),
3789 diag::warn_initializer_out_of_order);
3790
Francois Pichetd583da02010-12-04 09:14:42 +00003791 if (PrevInit->isAnyMemberInitializer())
3792 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003793 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003794 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003795
Francois Pichetd583da02010-12-04 09:14:42 +00003796 if (Init->isAnyMemberInitializer())
3797 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003798 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003799 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003800
3801 // Move back to the initializer's location in the ideal list.
3802 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3803 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003804 break;
John McCallbb7b6582010-04-10 07:37:23 +00003805
3806 assert(IdealIndex != NumIdealInits &&
3807 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003808 }
John McCallbb7b6582010-04-10 07:37:23 +00003809
3810 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003811 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003812}
3813
John McCall23eebd92010-04-10 09:28:51 +00003814namespace {
3815bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003816 CXXCtorInitializer *Init,
3817 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003818 if (!PrevInit) {
3819 PrevInit = Init;
3820 return false;
3821 }
3822
Douglas Gregorea306a12013-03-25 23:28:23 +00003823 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003824 S.Diag(Init->getSourceLocation(),
3825 diag::err_multiple_mem_initialization)
3826 << Field->getDeclName()
3827 << Init->getSourceRange();
3828 else {
John McCall424cec92011-01-19 06:33:43 +00003829 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003830 assert(BaseClass && "neither field nor base");
3831 S.Diag(Init->getSourceLocation(),
3832 diag::err_multiple_base_initialization)
3833 << QualType(BaseClass, 0)
3834 << Init->getSourceRange();
3835 }
3836 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3837 << 0 << PrevInit->getSourceRange();
3838
3839 return true;
3840}
3841
Alexis Hunt1d792652011-01-08 20:30:50 +00003842typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003843typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3844
3845bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003846 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003847 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003848 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003849 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003850 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003851
3852 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003853 if (Parent->isUnion()) {
3854 UnionEntry &En = Unions[Parent];
3855 if (En.first && En.first != Child) {
3856 S.Diag(Init->getSourceLocation(),
3857 diag::err_multiple_mem_union_initialization)
3858 << Field->getDeclName()
3859 << Init->getSourceRange();
3860 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3861 << 0 << En.second->getSourceRange();
3862 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003863 }
3864 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003865 En.first = Child;
3866 En.second = Init;
3867 }
David Blaikie0f65d592011-11-17 06:01:57 +00003868 if (!Parent->isAnonymousStructOrUnion())
3869 return false;
John McCall23eebd92010-04-10 09:28:51 +00003870 }
3871
3872 Child = Parent;
3873 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003874 }
John McCall23eebd92010-04-10 09:28:51 +00003875
3876 return false;
3877}
3878}
3879
Anders Carlssone857b292010-04-02 03:37:03 +00003880/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003881void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003882 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003883 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003884 bool AnyErrors) {
3885 if (!ConstructorDecl)
3886 return;
3887
3888 AdjustDeclIfTemplate(ConstructorDecl);
3889
3890 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003891 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003892
3893 if (!Constructor) {
3894 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3895 return;
3896 }
3897
John McCall23eebd92010-04-10 09:28:51 +00003898 // Mapping for the duplicate initializers check.
3899 // For member initializers, this is keyed with a FieldDecl*.
3900 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003901 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003902
3903 // Mapping for the inconsistent anonymous-union initializers check.
3904 RedundantUnionMap MemberUnions;
3905
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003906 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003907 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003908 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003909
Abramo Bagnara341d7832010-05-26 18:09:23 +00003910 // Set the source order index.
3911 Init->setSourceOrder(i);
3912
Francois Pichetd583da02010-12-04 09:14:42 +00003913 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003914 const void *Key = GetKeyForMember(Context, Init);
3915 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003916 CheckRedundantUnionInit(*this, Init, MemberUnions))
3917 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003918 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003919 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003920 if (CheckRedundantInit(*this, Init, Members[Key]))
3921 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003922 } else {
3923 assert(Init->isDelegatingInitializer());
3924 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003925 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003926 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003927 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003928 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003929 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003930 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003931 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003932 // Return immediately as the initializer is set.
3933 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003934 }
Anders Carlssone857b292010-04-02 03:37:03 +00003935 }
3936
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003937 if (HadError)
3938 return;
3939
David Blaikie3fc2f912013-01-17 05:26:25 +00003940 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003941
David Blaikie3fc2f912013-01-17 05:26:25 +00003942 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003943
Richard Trieuef64e942013-10-25 00:56:00 +00003944 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003945}
3946
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003947void
John McCalla6309952010-03-16 21:39:52 +00003948Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3949 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003950 // Ignore dependent contexts. Also ignore unions, since their members never
3951 // have destructors implicitly called.
3952 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003953 return;
John McCall1064d7e2010-03-16 05:22:47 +00003954
3955 // FIXME: all the access-control diagnostics are positioned on the
3956 // field/base declaration. That's probably good; that said, the
3957 // user might reasonably want to know why the destructor is being
3958 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003959
Anders Carlssondee9a302009-11-17 04:44:12 +00003960 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003961 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003962 if (Field->isInvalidDecl())
3963 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003964
3965 // Don't destroy incomplete or zero-length arrays.
3966 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3967 continue;
3968
Anders Carlssondee9a302009-11-17 04:44:12 +00003969 QualType FieldType = Context.getBaseElementType(Field->getType());
3970
3971 const RecordType* RT = FieldType->getAs<RecordType>();
3972 if (!RT)
3973 continue;
3974
3975 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003976 if (FieldClassDecl->isInvalidDecl())
3977 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003978 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003979 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003980 // The destructor for an implicit anonymous union member is never invoked.
3981 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3982 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003983
Douglas Gregore71edda2010-07-01 22:47:18 +00003984 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003985 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003986 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003987 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003988 << Field->getDeclName()
3989 << FieldType);
3990
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003991 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003992 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003993 }
3994
John McCall1064d7e2010-03-16 05:22:47 +00003995 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3996
Anders Carlssondee9a302009-11-17 04:44:12 +00003997 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003998 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003999 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004000 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004001
4002 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004003 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004004 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004005
John McCall1064d7e2010-03-16 05:22:47 +00004006 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004007 // If our base class is invalid, we probably can't get its dtor anyway.
4008 if (BaseClassDecl->isInvalidDecl())
4009 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004010 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004011 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004012
Douglas Gregore71edda2010-07-01 22:47:18 +00004013 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004014 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004015
4016 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004017 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004018 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004019 << Base.getType()
4020 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004021 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004022
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004023 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004024 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004025 }
4026
4027 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004028 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004029 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004030 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004031
4032 // Ignore direct virtual bases.
4033 if (DirectVirtualBases.count(RT))
4034 continue;
4035
John McCall1064d7e2010-03-16 05:22:47 +00004036 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004037 // If our base class is invalid, we probably can't get its dtor anyway.
4038 if (BaseClassDecl->isInvalidDecl())
4039 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004040 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004041 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004042
Douglas Gregore71edda2010-07-01 22:47:18 +00004043 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004044 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004045 if (CheckDestructorAccess(
4046 ClassDecl->getLocation(), Dtor,
4047 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004048 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004049 Context.getTypeDeclType(ClassDecl)) ==
4050 AR_accessible) {
4051 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004052 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004053 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004054 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004055 }
John McCall1064d7e2010-03-16 05:22:47 +00004056
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004057 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004058 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004059 }
4060}
4061
John McCall48871652010-08-21 09:40:31 +00004062void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004063 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004064 return;
Mike Stump11289f42009-09-09 15:08:12 +00004065
Mike Stump11289f42009-09-09 15:08:12 +00004066 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004067 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004068 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004069 DiagnoseUninitializedFields(*this, Constructor);
4070 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004071}
4072
Mike Stump11289f42009-09-09 15:08:12 +00004073bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004074 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004075 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4076 unsigned DiagID;
4077 AbstractDiagSelID SelID;
4078
4079 public:
4080 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4081 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004082
Craig Toppera798a9d2014-03-02 09:32:10 +00004083 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004084 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004085 if (SelID == -1)
4086 S.Diag(Loc, DiagID) << T;
4087 else
4088 S.Diag(Loc, DiagID) << SelID << T;
4089 }
4090 } Diagnoser(DiagID, SelID);
4091
4092 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004093}
4094
Anders Carlssoneabf7702009-08-27 00:13:57 +00004095bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004096 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004097 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004098 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004099
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004100 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004101 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004102
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004103 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004104 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004105 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004106 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004107
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004108 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004109 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004112 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004113 if (!RT)
4114 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004115
John McCall67da35c2010-02-04 22:26:26 +00004116 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004117
John McCall02db245d2010-08-18 09:41:07 +00004118 // We can't answer whether something is abstract until it has a
4119 // definition. If it's currently being defined, we'll walk back
4120 // over all the declarations when we have a full definition.
4121 const CXXRecordDecl *Def = RD->getDefinition();
4122 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004123 return false;
4124
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004125 if (!RD->isAbstract())
4126 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregorae298422012-05-04 17:09:59 +00004128 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004129 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004130
John McCall02db245d2010-08-18 09:41:07 +00004131 return true;
4132}
4133
4134void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4135 // Check if we've already emitted the list of pure virtual functions
4136 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004137 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004138 return;
Mike Stump11289f42009-09-09 15:08:12 +00004139
Richard Smithbc46e432013-07-22 02:56:56 +00004140 // If the diagnostic is suppressed, don't emit the notes. We're only
4141 // going to emit them once, so try to attach them to a diagnostic we're
4142 // actually going to show.
4143 if (Diags.isLastDiagnosticIgnored())
4144 return;
4145
Douglas Gregor4165bd62010-03-23 23:47:56 +00004146 CXXFinalOverriderMap FinalOverriders;
4147 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004148
Anders Carlssona2f74f32010-06-03 01:00:02 +00004149 // Keep a set of seen pure methods so we won't diagnose the same method
4150 // more than once.
4151 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4152
Douglas Gregor4165bd62010-03-23 23:47:56 +00004153 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4154 MEnd = FinalOverriders.end();
4155 M != MEnd;
4156 ++M) {
4157 for (OverridingMethods::iterator SO = M->second.begin(),
4158 SOEnd = M->second.end();
4159 SO != SOEnd; ++SO) {
4160 // C++ [class.abstract]p4:
4161 // A class is abstract if it contains or inherits at least one
4162 // pure virtual function for which the final overrider is pure
4163 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004164
Douglas Gregor4165bd62010-03-23 23:47:56 +00004165 //
4166 if (SO->second.size() != 1)
4167 continue;
4168
4169 if (!SO->second.front().Method->isPure())
4170 continue;
4171
Anders Carlssona2f74f32010-06-03 01:00:02 +00004172 if (!SeenPureMethods.insert(SO->second.front().Method))
4173 continue;
4174
Douglas Gregor4165bd62010-03-23 23:47:56 +00004175 Diag(SO->second.front().Method->getLocation(),
4176 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004177 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004178 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004179 }
4180
4181 if (!PureVirtualClassDiagSet)
4182 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4183 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004184}
4185
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004186namespace {
John McCall02db245d2010-08-18 09:41:07 +00004187struct AbstractUsageInfo {
4188 Sema &S;
4189 CXXRecordDecl *Record;
4190 CanQualType AbstractType;
4191 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004192
John McCall02db245d2010-08-18 09:41:07 +00004193 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4194 : S(S), Record(Record),
4195 AbstractType(S.Context.getCanonicalType(
4196 S.Context.getTypeDeclType(Record))),
4197 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004198
John McCall02db245d2010-08-18 09:41:07 +00004199 void DiagnoseAbstractType() {
4200 if (Invalid) return;
4201 S.DiagnoseAbstractType(Record);
4202 Invalid = true;
4203 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004204
John McCall02db245d2010-08-18 09:41:07 +00004205 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4206};
4207
4208struct CheckAbstractUsage {
4209 AbstractUsageInfo &Info;
4210 const NamedDecl *Ctx;
4211
4212 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4213 : Info(Info), Ctx(Ctx) {}
4214
4215 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4216 switch (TL.getTypeLocClass()) {
4217#define ABSTRACT_TYPELOC(CLASS, PARENT)
4218#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004219 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004220#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004221 }
John McCall02db245d2010-08-18 09:41:07 +00004222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall02db245d2010-08-18 09:41:07 +00004224 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004225 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004226 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4227 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004228 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004229
4230 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004231 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004232 }
John McCall02db245d2010-08-18 09:41:07 +00004233 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004234
John McCall02db245d2010-08-18 09:41:07 +00004235 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4236 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4237 }
Mike Stump11289f42009-09-09 15:08:12 +00004238
John McCall02db245d2010-08-18 09:41:07 +00004239 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4240 // Visit the type parameters from a permissive context.
4241 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4242 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4243 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4244 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4245 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4246 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004247 }
John McCall02db245d2010-08-18 09:41:07 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
John McCall02db245d2010-08-18 09:41:07 +00004250 // Visit pointee types from a permissive context.
4251#define CheckPolymorphic(Type) \
4252 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4253 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4254 }
4255 CheckPolymorphic(PointerTypeLoc)
4256 CheckPolymorphic(ReferenceTypeLoc)
4257 CheckPolymorphic(MemberPointerTypeLoc)
4258 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004259 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004260
John McCall02db245d2010-08-18 09:41:07 +00004261 /// Handle all the types we haven't given a more specific
4262 /// implementation for above.
4263 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4264 // Every other kind of type that we haven't called out already
4265 // that has an inner type is either (1) sugar or (2) contains that
4266 // inner type in some way as a subobject.
4267 if (TypeLoc Next = TL.getNextTypeLoc())
4268 return Visit(Next, Sel);
4269
4270 // If there's no inner type and we're in a permissive context,
4271 // don't diagnose.
4272 if (Sel == Sema::AbstractNone) return;
4273
4274 // Check whether the type matches the abstract type.
4275 QualType T = TL.getType();
4276 if (T->isArrayType()) {
4277 Sel = Sema::AbstractArrayType;
4278 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004279 }
John McCall02db245d2010-08-18 09:41:07 +00004280 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4281 if (CT != Info.AbstractType) return;
4282
4283 // It matched; do some magic.
4284 if (Sel == Sema::AbstractArrayType) {
4285 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4286 << T << TL.getSourceRange();
4287 } else {
4288 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4289 << Sel << T << TL.getSourceRange();
4290 }
4291 Info.DiagnoseAbstractType();
4292 }
4293};
4294
4295void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4296 Sema::AbstractDiagSelID Sel) {
4297 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4298}
4299
4300}
4301
4302/// Check for invalid uses of an abstract type in a method declaration.
4303static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4304 CXXMethodDecl *MD) {
4305 // No need to do the check on definitions, which require that
4306 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004307 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004308 return;
4309
4310 // For safety's sake, just ignore it if we don't have type source
4311 // information. This should never happen for non-implicit methods,
4312 // but...
4313 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4314 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4315}
4316
4317/// Check for invalid uses of an abstract type within a class definition.
4318static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4319 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004320 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004321 if (D->isImplicit()) continue;
4322
4323 // Methods and method templates.
4324 if (isa<CXXMethodDecl>(D)) {
4325 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4326 } else if (isa<FunctionTemplateDecl>(D)) {
4327 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4328 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4329
4330 // Fields and static variables.
4331 } else if (isa<FieldDecl>(D)) {
4332 FieldDecl *FD = cast<FieldDecl>(D);
4333 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4334 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4335 } else if (isa<VarDecl>(D)) {
4336 VarDecl *VD = cast<VarDecl>(D);
4337 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4338 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4339
4340 // Nested classes and class templates.
4341 } else if (isa<CXXRecordDecl>(D)) {
4342 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4343 } else if (isa<ClassTemplateDecl>(D)) {
4344 CheckAbstractClassUsage(Info,
4345 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4346 }
4347 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004348}
4349
Hans Wennborg853ae942014-05-30 16:59:42 +00004350/// \brief Check class-level dllimport/dllexport attribute.
4351static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4352 Attr *ClassAttr = getDLLAttr(Class);
4353 if (!ClassAttr)
4354 return;
4355
4356 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4357
4358 // Force declaration of implicit members so they can inherit the attribute.
4359 S.ForceDeclarationOfImplicitMembers(Class);
4360
4361 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4362 // seem to be true in practice?
4363
4364 // FIXME: We also need to propagate the attribute upwards to class template
4365 // specialization bases.
4366
4367 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004368 VarDecl *VD = dyn_cast<VarDecl>(Member);
4369 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4370
4371 // Only methods and static fields inherit the attributes.
4372 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004373 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004374
4375 // Don't process deleted methods.
4376 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004377 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004378
Hans Wennborge8ad3832014-06-11 22:44:39 +00004379 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4380 MD->isInlined()) {
4381 // Current MSVC versions don't export the move assignment operators, so
4382 // don't attempt to import them if we have a definition.
4383 continue;
4384 }
4385
Hans Wennborg496524b2014-05-31 02:08:49 +00004386 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) {
4387 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4388 !MemberAttr->isInherited()) {
4389 S.Diag(MemberAttr->getLocation(),
4390 diag::err_attribute_dll_member_of_dll_class)
4391 << MemberAttr << ClassAttr;
4392 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4393 Member->setInvalidDecl();
4394 continue;
4395 }
4396 } else {
4397 auto *NewAttr =
4398 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4399 NewAttr->setInherited(true);
4400 Member->addAttr(NewAttr);
4401 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004402
4403 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
4404 if (ClassExported) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004405 if (MD->isUserProvided()) {
4406 // Instantiate non-default methods.
4407 S.MarkFunctionReferenced(Class->getLocation(), MD);
4408 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4409 MD->isCopyAssignmentOperator() ||
4410 MD->isMoveAssignmentOperator()) {
Alp Toker15e62a32014-06-06 12:02:07 +00004411 // Instantiate non-trivial or explicitly defaulted methods, and the
Hans Wennborg853ae942014-05-30 16:59:42 +00004412 // copy assignment / move assignment operators.
4413 S.MarkFunctionReferenced(Class->getLocation(), MD);
4414 // Resolve its exception specification; CodeGen needs it.
4415 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4416 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4417 S.ActOnFinishInlineMethodDef(MD);
4418 }
4419 }
4420 }
4421 }
4422}
4423
Douglas Gregorc99f1552009-12-03 18:33:45 +00004424/// \brief Perform semantic checks on a class definition that has been
4425/// completing, introducing implicitly-declared members, checking for
4426/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004427void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004428 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004429 return;
4430
John McCall02db245d2010-08-18 09:41:07 +00004431 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4432 AbstractUsageInfo Info(*this, Record);
4433 CheckAbstractClassUsage(Info, Record);
4434 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004435
4436 // If this is not an aggregate type and has no user-declared constructor,
4437 // complain about any non-static data members of reference or const scalar
4438 // type, since they will never get initializers.
4439 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004440 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4441 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004442 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004443 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004444 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004445 continue;
4446
Douglas Gregor454a5b62010-04-15 00:00:53 +00004447 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004448 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004449 if (!Complained) {
4450 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4451 << Record->getTagKind() << Record;
4452 Complained = true;
4453 }
4454
4455 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4456 << F->getType()->isReferenceType()
4457 << F->getDeclName();
4458 }
4459 }
4460 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004461
Anders Carlssone771e762011-01-25 18:08:22 +00004462 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004463 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004464
4465 if (Record->getIdentifier()) {
4466 // C++ [class.mem]p13:
4467 // If T is the name of a class, then each of the following shall have a
4468 // name different from T:
4469 // - every member of every anonymous union that is a member of class T.
4470 //
4471 // C++ [class.mem]p14:
4472 // In addition, if class T has a user-declared constructor (12.1), every
4473 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004474 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4475 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4476 ++I) {
4477 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004478 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4479 isa<IndirectFieldDecl>(D)) {
4480 Diag(D->getLocation(), diag::err_member_name_of_class)
4481 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004482 break;
4483 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004484 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004485 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004486
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004487 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004488 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004489 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004490 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4491 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004492 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4493 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4494 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004495
David Majnemera5433082013-10-18 00:33:31 +00004496 if (Record->isAbstract()) {
4497 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4498 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4499 << FA->isSpelledAsSealed();
4500 DiagnoseAbstractType(Record);
4501 }
David Blaikie348df502012-09-21 03:21:07 +00004502 }
4503
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004504 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004505 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004506 // See if a method overloads virtual methods in a base
4507 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004508 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004509 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004510
4511 // Check whether the explicitly-defaulted special members are valid.
4512 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004513 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004514
4515 // For an explicitly defaulted or deleted special member, we defer
4516 // determining triviality until the class is complete. That time is now!
4517 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004518 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004519 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004520 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004521
4522 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004523 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004524 }
4525 }
4526 }
4527 }
4528
4529 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4530 // function that is not a constructor declares that member function to be
4531 // const. [...] The class of which that function is a member shall be
4532 // a literal type.
4533 //
4534 // If the class has virtual bases, any constexpr members will already have
4535 // been diagnosed by the checks performed on the member declaration, so
4536 // suppress this (less useful) diagnostic.
4537 //
4538 // We delay this until we know whether an explicitly-defaulted (or deleted)
4539 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004540 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004541 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004542 for (const auto *M : Record->methods()) {
4543 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004544 switch (Record->getTemplateSpecializationKind()) {
4545 case TSK_ImplicitInstantiation:
4546 case TSK_ExplicitInstantiationDeclaration:
4547 case TSK_ExplicitInstantiationDefinition:
4548 // If a template instantiates to a non-literal type, but its members
4549 // instantiate to constexpr functions, the template is technically
4550 // ill-formed, but we allow it for sanity.
4551 continue;
4552
4553 case TSK_Undeclared:
4554 case TSK_ExplicitSpecialization:
4555 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4556 diag::err_constexpr_method_non_literal);
4557 break;
4558 }
4559
4560 // Only produce one error per class.
4561 break;
4562 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004563 }
4564 }
Sebastian Redl08905022011-02-05 19:23:19 +00004565
John McCall95833f32014-02-27 20:30:49 +00004566 // ms_struct is a request to use the same ABI rules as MSVC. Check
4567 // whether this class uses any C++ features that are implemented
4568 // completely differently in MSVC, and if so, emit a diagnostic.
4569 // That diagnostic defaults to an error, but we allow projects to
4570 // map it down to a warning (or ignore it). It's a fairly common
4571 // practice among users of the ms_struct pragma to mass-annotate
4572 // headers, sweeping up a bunch of types that the project doesn't
4573 // really rely on MSVC-compatible layout for. We must therefore
4574 // support "ms_struct except for C++ stuff" as a secondary ABI.
4575 if (Record->isMsStruct(Context) &&
4576 (Record->isPolymorphic() || Record->getNumBases())) {
4577 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004578 }
4579
Richard Smithc2bc61b2013-03-18 21:12:30 +00004580 // Declare inheriting constructors. We do this eagerly here because:
4581 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004582 // constructors from different classes.
4583 // - The lazy declaration of the other implicit constructors is so as to not
4584 // waste space and performance on classes that are not meant to be
4585 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004586 // have inheriting constructors.
4587 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004588
4589 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004590}
4591
Richard Smith41c35d62013-11-27 03:39:20 +00004592/// Look up the special member function that would be called by a special
4593/// member function for a subobject of class type.
4594///
4595/// \param Class The class type of the subobject.
4596/// \param CSM The kind of special member function.
4597/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4598/// \param ConstRHS True if this is a copy operation with a const object
4599/// on its RHS, that is, if the argument to the outer special member
4600/// function is 'const' and this is not a field marked 'mutable'.
4601static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4602 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4603 unsigned FieldQuals, bool ConstRHS) {
4604 unsigned LHSQuals = 0;
4605 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4606 LHSQuals = FieldQuals;
4607
4608 unsigned RHSQuals = FieldQuals;
4609 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4610 RHSQuals = 0;
4611 else if (ConstRHS)
4612 RHSQuals |= Qualifiers::Const;
4613
4614 return S.LookupSpecialMember(Class, CSM,
4615 RHSQuals & Qualifiers::Const,
4616 RHSQuals & Qualifiers::Volatile,
4617 false,
4618 LHSQuals & Qualifiers::Const,
4619 LHSQuals & Qualifiers::Volatile);
4620}
4621
Richard Smithb5800092012-06-10 05:43:50 +00004622/// Is the special member function which would be selected to perform the
4623/// specified operation on the specified class type a constexpr constructor?
4624static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4625 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004626 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004627 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004628 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004629 if (!SMOR || !SMOR->getMethod())
4630 // A constructor we wouldn't select can't be "involved in initializing"
4631 // anything.
4632 return true;
4633 return SMOR->getMethod()->isConstexpr();
4634}
4635
4636/// Determine whether the specified special member function would be constexpr
4637/// if it were implicitly defined.
4638static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4639 Sema::CXXSpecialMember CSM,
4640 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004641 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004642 return false;
4643
4644 // C++11 [dcl.constexpr]p4:
4645 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004646 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004647 switch (CSM) {
4648 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004649 // Since default constructor lookup is essentially trivial (and cannot
4650 // involve, for instance, template instantiation), we compute whether a
4651 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4652 //
4653 // This is important for performance; we need to know whether the default
4654 // constructor is constexpr to determine whether the type is a literal type.
4655 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4656
Richard Smithb5800092012-06-10 05:43:50 +00004657 case Sema::CXXCopyConstructor:
4658 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004659 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004660 break;
4661
4662 case Sema::CXXCopyAssignment:
4663 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004664 if (!S.getLangOpts().CPlusPlus1y)
4665 return false;
4666 // In C++1y, we need to perform overload resolution.
4667 Ctor = false;
4668 break;
4669
Richard Smithb5800092012-06-10 05:43:50 +00004670 case Sema::CXXDestructor:
4671 case Sema::CXXInvalid:
4672 return false;
4673 }
4674
4675 // -- if the class is a non-empty union, or for each non-empty anonymous
4676 // union member of a non-union class, exactly one non-static data member
4677 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004678 //
4679 // If we squint, this is guaranteed, since exactly one non-static data member
4680 // will be initialized (if the constructor isn't deleted), we just don't know
4681 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004682 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004683 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004684
4685 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004686 if (Ctor && ClassDecl->getNumVBases())
4687 return false;
4688
4689 // C++1y [class.copy]p26:
4690 // -- [the class] is a literal type, and
4691 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004692 return false;
4693
4694 // -- every constructor involved in initializing [...] base class
4695 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004696 // -- the assignment operator selected to copy/move each direct base
4697 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004698 for (const auto &B : ClassDecl->bases()) {
4699 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004700 if (!BaseType) continue;
4701
4702 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004703 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004704 return false;
4705 }
4706
4707 // -- every constructor involved in initializing non-static data members
4708 // [...] shall be a constexpr constructor;
4709 // -- every non-static data member and base class sub-object shall be
4710 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004711 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004712 // thereof), the assignment operator selected to copy/move that member is
4713 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004714 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004715 if (F->isInvalidDecl())
4716 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004717 QualType BaseType = S.Context.getBaseElementType(F->getType());
4718 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004719 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004720 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4721 BaseType.getCVRQualifiers(),
4722 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004723 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004724 }
4725 }
4726
4727 // All OK, it's constexpr!
4728 return true;
4729}
4730
Richard Smithd3b5c9082012-07-27 04:22:15 +00004731static Sema::ImplicitExceptionSpecification
4732computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4733 switch (S.getSpecialMember(MD)) {
4734 case Sema::CXXDefaultConstructor:
4735 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4736 case Sema::CXXCopyConstructor:
4737 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4738 case Sema::CXXCopyAssignment:
4739 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4740 case Sema::CXXMoveConstructor:
4741 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4742 case Sema::CXXMoveAssignment:
4743 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4744 case Sema::CXXDestructor:
4745 return S.ComputeDefaultedDtorExceptionSpec(MD);
4746 case Sema::CXXInvalid:
4747 break;
4748 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004749 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4750 "only special members have implicit exception specs");
4751 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004752}
4753
Reid Kleckner78af0702013-08-27 23:08:25 +00004754static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4755 CXXMethodDecl *MD) {
4756 FunctionProtoType::ExtProtoInfo EPI;
4757
4758 // Build an exception specification pointing back at this member.
4759 EPI.ExceptionSpecType = EST_Unevaluated;
4760 EPI.ExceptionSpecDecl = MD;
4761
4762 // Set the calling convention to the default for C++ instance methods.
4763 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4764 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4765 /*IsCXXMethod=*/true));
4766 return EPI;
4767}
4768
Richard Smithd3b5c9082012-07-27 04:22:15 +00004769void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4770 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4771 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4772 return;
4773
Richard Smith7f782272012-07-30 23:48:14 +00004774 // Evaluate the exception specification.
4775 ImplicitExceptionSpecification ExceptSpec =
4776 computeImplicitExceptionSpec(*this, Loc, MD);
4777
Richard Smith564417a2014-03-20 21:47:22 +00004778 FunctionProtoType::ExtProtoInfo EPI;
4779 ExceptSpec.getEPI(EPI);
4780
Richard Smith7f782272012-07-30 23:48:14 +00004781 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004782 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004783
4784 // A user-provided destructor can be defined outside the class. When that
4785 // happens, be sure to update the exception specification on both
4786 // declarations.
4787 const FunctionProtoType *CanonicalFPT =
4788 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4789 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004790 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004791}
4792
Richard Smithb9e90b12012-05-15 04:39:51 +00004793void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4794 CXXRecordDecl *RD = MD->getParent();
4795 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004796
Richard Smithb9e90b12012-05-15 04:39:51 +00004797 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4798 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004799
4800 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004801 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004802 bool First = MD == MD->getCanonicalDecl();
4803
4804 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004805
4806 // C++11 [dcl.fct.def.default]p1:
4807 // A function that is explicitly defaulted shall
4808 // -- be a special member function (checked elsewhere),
4809 // -- have the same type (except for ref-qualifiers, and except that a
4810 // copy operation can take a non-const reference) as an implicit
4811 // declaration, and
4812 // -- not have default arguments.
4813 unsigned ExpectedParams = 1;
4814 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4815 ExpectedParams = 0;
4816 if (MD->getNumParams() != ExpectedParams) {
4817 // This also checks for default arguments: a copy or move constructor with a
4818 // default argument is classified as a default constructor, and assignment
4819 // operations and destructors can't have default arguments.
4820 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4821 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004822 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004823 } else if (MD->isVariadic()) {
4824 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4825 << CSM << MD->getSourceRange();
4826 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004827 }
4828
Richard Smithb9e90b12012-05-15 04:39:51 +00004829 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004830
Richard Smithb5800092012-06-10 05:43:50 +00004831 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004832 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004833 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004834 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004835 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004836
Richard Smithb9e90b12012-05-15 04:39:51 +00004837 QualType ReturnType = Context.VoidTy;
4838 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4839 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004840 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004841 QualType ExpectedReturnType =
4842 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4843 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4844 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4845 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4846 HadError = true;
4847 }
4848
4849 // A defaulted special member cannot have cv-qualifiers.
4850 if (Type->getTypeQuals()) {
4851 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004852 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004853 HadError = true;
4854 }
4855 }
4856
4857 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004858 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004859 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004860 if (ExpectedParams && ArgType->isReferenceType()) {
4861 // Argument must be reference to possibly-const T.
4862 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004863 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004864
4865 if (ReferentType.isVolatileQualified()) {
4866 Diag(MD->getLocation(),
4867 diag::err_defaulted_special_member_volatile_param) << CSM;
4868 HadError = true;
4869 }
4870
Richard Smithb5800092012-06-10 05:43:50 +00004871 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004872 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4873 Diag(MD->getLocation(),
4874 diag::err_defaulted_special_member_copy_const_param)
4875 << (CSM == CXXCopyAssignment);
4876 // FIXME: Explain why this special member can't be const.
4877 } else {
4878 Diag(MD->getLocation(),
4879 diag::err_defaulted_special_member_move_const_param)
4880 << (CSM == CXXMoveAssignment);
4881 }
4882 HadError = true;
4883 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004884 } else if (ExpectedParams) {
4885 // A copy assignment operator can take its argument by value, but a
4886 // defaulted one cannot.
4887 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004888 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004889 HadError = true;
4890 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004891
Richard Smithcc36f692011-12-22 02:22:31 +00004892 // C++11 [dcl.fct.def.default]p2:
4893 // An explicitly-defaulted function may be declared constexpr only if it
4894 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004895 // Do not apply this rule to members of class templates, since core issue 1358
4896 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004897 // functions which cannot be constexpr (for non-constructors in C++11 and for
4898 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004899 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4900 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004901 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4902 : isa<CXXConstructorDecl>(MD)) &&
4903 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004904 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4905 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004906 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004907 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004908 }
Richard Smithbd305122012-12-11 01:14:52 +00004909
Richard Smithcc36f692011-12-22 02:22:31 +00004910 // and may have an explicit exception-specification only if it is compatible
4911 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004912 if (Type->hasExceptionSpec()) {
4913 // Delay the check if this is the first declaration of the special member,
4914 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004915 if (First) {
4916 // If the exception specification needs to be instantiated, do so now,
4917 // before we clobber it with an EST_Unevaluated specification below.
4918 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4919 InstantiateExceptionSpec(MD->getLocStart(), MD);
4920 Type = MD->getType()->getAs<FunctionProtoType>();
4921 }
Richard Smithbd305122012-12-11 01:14:52 +00004922 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004923 } else
Richard Smithbd305122012-12-11 01:14:52 +00004924 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4925 }
Richard Smithcc36f692011-12-22 02:22:31 +00004926
4927 // If a function is explicitly defaulted on its first declaration,
4928 if (First) {
4929 // -- it is implicitly considered to be constexpr if the implicit
4930 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004931 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004932
Richard Smithb9e90b12012-05-15 04:39:51 +00004933 // -- it is implicitly considered to have the same exception-specification
4934 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004935 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4936 EPI.ExceptionSpecType = EST_Unevaluated;
4937 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004938 MD->setType(Context.getFunctionType(ReturnType,
4939 ArrayRef<QualType>(&ArgType,
4940 ExpectedParams),
4941 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004942 }
4943
Richard Smithb9e90b12012-05-15 04:39:51 +00004944 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004945 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004946 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004947 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004948 // C++11 [dcl.fct.def.default]p4:
4949 // [For a] user-provided explicitly-defaulted function [...] if such a
4950 // function is implicitly defined as deleted, the program is ill-formed.
4951 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004952 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004953 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004954 }
4955 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004956
Richard Smithb9e90b12012-05-15 04:39:51 +00004957 if (HadError)
4958 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004959}
4960
Richard Smithbd305122012-12-11 01:14:52 +00004961/// Check whether the exception specification provided for an
4962/// explicitly-defaulted special member matches the exception specification
4963/// that would have been generated for an implicit special member, per
4964/// C++11 [dcl.fct.def.default]p2.
4965void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4966 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4967 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004968 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4969 /*IsCXXMethod=*/true);
4970 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004971 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4972 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004973 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004974
4975 // Ensure that it matches.
4976 CheckEquivalentExceptionSpec(
4977 PDiag(diag::err_incorrect_defaulted_exception_spec)
4978 << getSpecialMember(MD), PDiag(),
4979 ImplicitType, SourceLocation(),
4980 SpecifiedType, MD->getLocation());
4981}
4982
Alp Tokerae3a9442013-10-18 05:54:19 +00004983void Sema::CheckDelayedMemberExceptionSpecs() {
4984 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4985 2> Checks;
4986 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004987
Alp Tokerae3a9442013-10-18 05:54:19 +00004988 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4989 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4990
4991 // Perform any deferred checking of exception specifications for virtual
4992 // destructors.
4993 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4994 const CXXDestructorDecl *Dtor = Checks[i].first;
4995 assert(!Dtor->getParent()->isDependentType() &&
4996 "Should not ever add destructors of templates into the list.");
4997 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4998 }
4999
5000 // Check that any explicitly-defaulted methods have exception specifications
5001 // compatible with their implicit exception specifications.
5002 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5003 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5004 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005005}
5006
Richard Smithd951a1d2012-02-18 02:02:13 +00005007namespace {
5008struct SpecialMemberDeletionInfo {
5009 Sema &S;
5010 CXXMethodDecl *MD;
5011 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005012 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005013
5014 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005015 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005016 SourceLocation Loc;
5017
5018 bool AllFieldsAreConst;
5019
5020 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005021 Sema::CXXSpecialMember CSM, bool Diagnose)
5022 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005023 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005024 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005025 AllFieldsAreConst(true) {
5026 switch (CSM) {
5027 case Sema::CXXDefaultConstructor:
5028 case Sema::CXXCopyConstructor:
5029 IsConstructor = true;
5030 break;
5031 case Sema::CXXMoveConstructor:
5032 IsConstructor = true;
5033 IsMove = true;
5034 break;
5035 case Sema::CXXCopyAssignment:
5036 IsAssignment = true;
5037 break;
5038 case Sema::CXXMoveAssignment:
5039 IsAssignment = true;
5040 IsMove = true;
5041 break;
5042 case Sema::CXXDestructor:
5043 break;
5044 case Sema::CXXInvalid:
5045 llvm_unreachable("invalid special member kind");
5046 }
5047
5048 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005049 if (const ReferenceType *RT =
5050 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5051 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005052 }
5053 }
5054
5055 bool inUnion() const { return MD->getParent()->isUnion(); }
5056
5057 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005058 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005059 unsigned Quals, bool IsMutable) {
5060 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5061 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005062 }
5063
Richard Smith852265f2012-03-30 20:53:28 +00005064 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005065
Richard Smith852265f2012-03-30 20:53:28 +00005066 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005067 bool shouldDeleteForField(FieldDecl *FD);
5068 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005069
Richard Smithaf136f82012-07-18 03:51:16 +00005070 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5071 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005072 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5073 Sema::SpecialMemberOverloadResult *SMOR,
5074 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005075
5076 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005077};
5078}
5079
John McCalld4274212012-04-09 20:53:23 +00005080/// Is the given special member inaccessible when used on the given
5081/// sub-object.
5082bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5083 CXXMethodDecl *target) {
5084 /// If we're operating on a base class, the object type is the
5085 /// type of this special member.
5086 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005087 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005088 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5089 objectTy = S.Context.getTypeDeclType(MD->getParent());
5090 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5091
5092 // If we're operating on a field, the object type is the type of the field.
5093 } else {
5094 objectTy = S.Context.getTypeDeclType(target->getParent());
5095 }
5096
5097 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5098}
5099
Richard Smith852265f2012-03-30 20:53:28 +00005100/// Check whether we should delete a special member due to the implicit
5101/// definition containing a call to a special member of a subobject.
5102bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5103 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5104 bool IsDtorCallInCtor) {
5105 CXXMethodDecl *Decl = SMOR->getMethod();
5106 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5107
5108 int DiagKind = -1;
5109
5110 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5111 DiagKind = !Decl ? 0 : 1;
5112 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5113 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005114 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005115 DiagKind = 3;
5116 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5117 !Decl->isTrivial()) {
5118 // A member of a union must have a trivial corresponding special member.
5119 // As a weird special case, a destructor call from a union's constructor
5120 // must be accessible and non-deleted, but need not be trivial. Such a
5121 // destructor is never actually called, but is semantically checked as
5122 // if it were.
5123 DiagKind = 4;
5124 }
5125
5126 if (DiagKind == -1)
5127 return false;
5128
5129 if (Diagnose) {
5130 if (Field) {
5131 S.Diag(Field->getLocation(),
5132 diag::note_deleted_special_member_class_subobject)
5133 << CSM << MD->getParent() << /*IsField*/true
5134 << Field << DiagKind << IsDtorCallInCtor;
5135 } else {
5136 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5137 S.Diag(Base->getLocStart(),
5138 diag::note_deleted_special_member_class_subobject)
5139 << CSM << MD->getParent() << /*IsField*/false
5140 << Base->getType() << DiagKind << IsDtorCallInCtor;
5141 }
5142
5143 if (DiagKind == 1)
5144 S.NoteDeletedFunction(Decl);
5145 // FIXME: Explain inaccessibility if DiagKind == 3.
5146 }
5147
5148 return true;
5149}
5150
Richard Smith921bd202012-02-26 09:11:52 +00005151/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005152/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005153bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005154 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005155 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005156 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005157
5158 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005159 // -- any direct or virtual base class, or non-static data member with no
5160 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005161 // either M has no default constructor or overload resolution as applied
5162 // to M's default constructor results in an ambiguity or in a function
5163 // that is deleted or inaccessible
5164 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5165 // -- a direct or virtual base class B that cannot be copied/moved because
5166 // overload resolution, as applied to B's corresponding special member,
5167 // results in an ambiguity or a function that is deleted or inaccessible
5168 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005169 // C++11 [class.dtor]p5:
5170 // -- any direct or virtual base class [...] has a type with a destructor
5171 // that is deleted or inaccessible
5172 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005173 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005174 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5175 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005176 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005177
Richard Smith852265f2012-03-30 20:53:28 +00005178 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5179 // -- any direct or virtual base class or non-static data member has a
5180 // type with a destructor that is deleted or inaccessible
5181 if (IsConstructor) {
5182 Sema::SpecialMemberOverloadResult *SMOR =
5183 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5184 false, false, false, false, false);
5185 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5186 return true;
5187 }
5188
Richard Smith921bd202012-02-26 09:11:52 +00005189 return false;
5190}
5191
5192/// Check whether we should delete a special member function due to the class
5193/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005194bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005195 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005196 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005197}
5198
5199/// Check whether we should delete a special member function due to the class
5200/// having a particular non-static data member.
5201bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5202 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5203 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5204
5205 if (CSM == Sema::CXXDefaultConstructor) {
5206 // For a default constructor, all references must be initialized in-class
5207 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005208 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5209 if (Diagnose)
5210 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5211 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005212 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005213 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005214 // C++11 [class.ctor]p5: any non-variant non-static data member of
5215 // const-qualified type (or array thereof) with no
5216 // brace-or-equal-initializer does not have a user-provided default
5217 // constructor.
5218 if (!inUnion() && FieldType.isConstQualified() &&
5219 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005220 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5221 if (Diagnose)
5222 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005223 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005224 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005225 }
5226
5227 if (inUnion() && !FieldType.isConstQualified())
5228 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005229 } else if (CSM == Sema::CXXCopyConstructor) {
5230 // For a copy constructor, data members must not be of rvalue reference
5231 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005232 if (FieldType->isRValueReferenceType()) {
5233 if (Diagnose)
5234 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5235 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005236 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005237 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005238 } else if (IsAssignment) {
5239 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005240 if (FieldType->isReferenceType()) {
5241 if (Diagnose)
5242 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5243 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005244 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005245 }
5246 if (!FieldRecord && FieldType.isConstQualified()) {
5247 // C++11 [class.copy]p23:
5248 // -- a non-static data member of const non-class type (or array thereof)
5249 if (Diagnose)
5250 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005251 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005252 return true;
5253 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005254 }
5255
5256 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005257 // Some additional restrictions exist on the variant members.
5258 if (!inUnion() && FieldRecord->isUnion() &&
5259 FieldRecord->isAnonymousStructOrUnion()) {
5260 bool AllVariantFieldsAreConst = true;
5261
Richard Smith5704fe82012-03-29 19:00:10 +00005262 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005263 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005264 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005265
5266 if (!UnionFieldType.isConstQualified())
5267 AllVariantFieldsAreConst = false;
5268
Richard Smith921bd202012-02-26 09:11:52 +00005269 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5270 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005271 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005272 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005273 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005274 }
5275
5276 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005277 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005278 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005279 if (Diagnose)
5280 S.Diag(FieldRecord->getLocation(),
5281 diag::note_deleted_default_ctor_all_const)
5282 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005283 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005284 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005285
Richard Smith5704fe82012-03-29 19:00:10 +00005286 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005287 // This is technically non-conformant, but sanity demands it.
5288 return false;
5289 }
5290
Richard Smithaf136f82012-07-18 03:51:16 +00005291 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5292 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005293 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005294 }
5295
5296 return false;
5297}
5298
5299/// C++11 [class.ctor] p5:
5300/// A defaulted default constructor for a class X is defined as deleted if
5301/// X is a union and all of its variant members are of const-qualified type.
5302bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005303 // This is a silly definition, because it gives an empty union a deleted
5304 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005305 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005306 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005307 if (Diagnose)
5308 S.Diag(MD->getParent()->getLocation(),
5309 diag::note_deleted_default_ctor_all_const)
5310 << MD->getParent() << /*not anonymous union*/0;
5311 return true;
5312 }
5313 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005314}
5315
5316/// Determine whether a defaulted special member function should be defined as
5317/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5318/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005319bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5320 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005321 if (MD->isInvalidDecl())
5322 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005323 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005324 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005325 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005326 return false;
5327
Richard Smithd951a1d2012-02-18 02:02:13 +00005328 // C++11 [expr.lambda.prim]p19:
5329 // The closure type associated with a lambda-expression has a
5330 // deleted (8.4.3) default constructor and a deleted copy
5331 // assignment operator.
5332 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005333 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5334 if (Diagnose)
5335 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005336 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005337 }
5338
Richard Smith6f1e2c62012-04-02 20:59:25 +00005339 // For an anonymous struct or union, the copy and assignment special members
5340 // will never be used, so skip the check. For an anonymous union declared at
5341 // namespace scope, the constructor and destructor are used.
5342 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5343 RD->isAnonymousStructOrUnion())
5344 return false;
5345
Richard Smith852265f2012-03-30 20:53:28 +00005346 // C++11 [class.copy]p7, p18:
5347 // If the class definition declares a move constructor or move assignment
5348 // operator, an implicitly declared copy constructor or copy assignment
5349 // operator is defined as deleted.
5350 if (MD->isImplicit() &&
5351 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005352 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005353
5354 // In Microsoft mode, a user-declared move only causes the deletion of the
5355 // corresponding copy operation, not both copy operations.
5356 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005357 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005358 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005359
5360 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005361 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005362 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005363 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005364 break;
5365 }
5366 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005367 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005368 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005369 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005370 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005371
5372 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005373 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005374 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005375 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005376 break;
5377 }
5378 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005379 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005380 }
5381
5382 if (UserDeclaredMove) {
5383 Diag(UserDeclaredMove->getLocation(),
5384 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005385 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005386 << UserDeclaredMove->isMoveAssignmentOperator();
5387 return true;
5388 }
5389 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005390
Richard Smith6f1e2c62012-04-02 20:59:25 +00005391 // Do access control from the special member function
5392 ContextRAII MethodContext(*this, MD);
5393
Richard Smith921bd202012-02-26 09:11:52 +00005394 // C++11 [class.dtor]p5:
5395 // -- for a virtual destructor, lookup of the non-array deallocation function
5396 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005397 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005398 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005399 DeclarationName Name =
5400 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5401 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005402 OperatorDelete, false)) {
5403 if (Diagnose)
5404 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005405 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005406 }
Richard Smith921bd202012-02-26 09:11:52 +00005407 }
5408
Richard Smith852265f2012-03-30 20:53:28 +00005409 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005410
Aaron Ballman574705e2014-03-13 15:41:46 +00005411 for (auto &BI : RD->bases())
5412 if (!BI.isVirtual() &&
5413 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005414 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005415
Richard Smithd1627032013-07-22 18:06:23 +00005416 // Per DR1611, do not consider virtual bases of constructors of abstract
5417 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005418 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005419 for (auto &BI : RD->vbases())
5420 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005421 return true;
5422 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005423
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005424 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005425 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005426 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005427 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005428
Richard Smithd951a1d2012-02-18 02:02:13 +00005429 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005430 return true;
5431
5432 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005433}
5434
Richard Smith92f241f2012-12-08 02:53:02 +00005435/// Perform lookup for a special member of the specified kind, and determine
5436/// whether it is trivial. If the triviality can be determined without the
5437/// lookup, skip it. This is intended for use when determining whether a
5438/// special member of a containing object is trivial, and thus does not ever
5439/// perform overload resolution for default constructors.
5440///
5441/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5442/// member that was most likely to be intended to be trivial, if any.
5443static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5444 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005445 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005446 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005447 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005448
5449 switch (CSM) {
5450 case Sema::CXXInvalid:
5451 llvm_unreachable("not a special member");
5452
5453 case Sema::CXXDefaultConstructor:
5454 // C++11 [class.ctor]p5:
5455 // A default constructor is trivial if:
5456 // - all the [direct subobjects] have trivial default constructors
5457 //
5458 // Note, no overload resolution is performed in this case.
5459 if (RD->hasTrivialDefaultConstructor())
5460 return true;
5461
5462 if (Selected) {
5463 // If there's a default constructor which could have been trivial, dig it
5464 // out. Otherwise, if there's any user-provided default constructor, point
5465 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005466 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005467 if (RD->needsImplicitDefaultConstructor())
5468 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005469 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005470 if (!CI->isDefaultConstructor())
5471 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005472 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005473 if (!DefCtor->isUserProvided())
5474 break;
5475 }
5476
5477 *Selected = DefCtor;
5478 }
5479
5480 return false;
5481
5482 case Sema::CXXDestructor:
5483 // C++11 [class.dtor]p5:
5484 // A destructor is trivial if:
5485 // - all the direct [subobjects] have trivial destructors
5486 if (RD->hasTrivialDestructor())
5487 return true;
5488
5489 if (Selected) {
5490 if (RD->needsImplicitDestructor())
5491 S.DeclareImplicitDestructor(RD);
5492 *Selected = RD->getDestructor();
5493 }
5494
5495 return false;
5496
5497 case Sema::CXXCopyConstructor:
5498 // C++11 [class.copy]p12:
5499 // A copy constructor is trivial if:
5500 // - the constructor selected to copy each direct [subobject] is trivial
5501 if (RD->hasTrivialCopyConstructor()) {
5502 if (Quals == Qualifiers::Const)
5503 // We must either select the trivial copy constructor or reach an
5504 // ambiguity; no need to actually perform overload resolution.
5505 return true;
5506 } else if (!Selected) {
5507 return false;
5508 }
5509 // In C++98, we are not supposed to perform overload resolution here, but we
5510 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5511 // cases like B as having a non-trivial copy constructor:
5512 // struct A { template<typename T> A(T&); };
5513 // struct B { mutable A a; };
5514 goto NeedOverloadResolution;
5515
5516 case Sema::CXXCopyAssignment:
5517 // C++11 [class.copy]p25:
5518 // A copy assignment operator is trivial if:
5519 // - the assignment operator selected to copy each direct [subobject] is
5520 // trivial
5521 if (RD->hasTrivialCopyAssignment()) {
5522 if (Quals == Qualifiers::Const)
5523 return true;
5524 } else if (!Selected) {
5525 return false;
5526 }
5527 // In C++98, we are not supposed to perform overload resolution here, but we
5528 // treat that as a language defect.
5529 goto NeedOverloadResolution;
5530
5531 case Sema::CXXMoveConstructor:
5532 case Sema::CXXMoveAssignment:
5533 NeedOverloadResolution:
5534 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005535 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005536
5537 // The standard doesn't describe how to behave if the lookup is ambiguous.
5538 // We treat it as not making the member non-trivial, just like the standard
5539 // mandates for the default constructor. This should rarely matter, because
5540 // the member will also be deleted.
5541 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5542 return true;
5543
5544 if (!SMOR->getMethod()) {
5545 assert(SMOR->getKind() ==
5546 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5547 return false;
5548 }
5549
5550 // We deliberately don't check if we found a deleted special member. We're
5551 // not supposed to!
5552 if (Selected)
5553 *Selected = SMOR->getMethod();
5554 return SMOR->getMethod()->isTrivial();
5555 }
5556
5557 llvm_unreachable("unknown special method kind");
5558}
5559
Benjamin Kramer3e350262013-02-15 12:30:38 +00005560static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005561 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005562 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005563 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005564
5565 // Look for constructor templates.
5566 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5567 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5568 if (CXXConstructorDecl *CD =
5569 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5570 return CD;
5571 }
5572
Craig Topperc3ec1492014-05-26 06:22:03 +00005573 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005574}
5575
5576/// The kind of subobject we are checking for triviality. The values of this
5577/// enumeration are used in diagnostics.
5578enum TrivialSubobjectKind {
5579 /// The subobject is a base class.
5580 TSK_BaseClass,
5581 /// The subobject is a non-static data member.
5582 TSK_Field,
5583 /// The object is actually the complete object.
5584 TSK_CompleteObject
5585};
5586
5587/// Check whether the special member selected for a given type would be trivial.
5588static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005589 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005590 Sema::CXXSpecialMember CSM,
5591 TrivialSubobjectKind Kind,
5592 bool Diagnose) {
5593 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5594 if (!SubRD)
5595 return true;
5596
5597 CXXMethodDecl *Selected;
5598 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005599 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005600 return true;
5601
5602 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005603 if (ConstRHS)
5604 SubType.addConst();
5605
Richard Smith92f241f2012-12-08 02:53:02 +00005606 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5607 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5608 << Kind << SubType.getUnqualifiedType();
5609 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5610 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5611 } else if (!Selected)
5612 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5613 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5614 else if (Selected->isUserProvided()) {
5615 if (Kind == TSK_CompleteObject)
5616 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5617 << Kind << SubType.getUnqualifiedType() << CSM;
5618 else {
5619 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5620 << Kind << SubType.getUnqualifiedType() << CSM;
5621 S.Diag(Selected->getLocation(), diag::note_declared_at);
5622 }
5623 } else {
5624 if (Kind != TSK_CompleteObject)
5625 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5626 << Kind << SubType.getUnqualifiedType() << CSM;
5627
5628 // Explain why the defaulted or deleted special member isn't trivial.
5629 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5630 }
5631 }
5632
5633 return false;
5634}
5635
5636/// Check whether the members of a class type allow a special member to be
5637/// trivial.
5638static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5639 Sema::CXXSpecialMember CSM,
5640 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005641 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005642 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5643 continue;
5644
5645 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5646
5647 // Pretend anonymous struct or union members are members of this class.
5648 if (FI->isAnonymousStructOrUnion()) {
5649 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5650 CSM, ConstArg, Diagnose))
5651 return false;
5652 continue;
5653 }
5654
5655 // C++11 [class.ctor]p5:
5656 // A default constructor is trivial if [...]
5657 // -- no non-static data member of its class has a
5658 // brace-or-equal-initializer
5659 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5660 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005661 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005662 return false;
5663 }
5664
5665 // Objective C ARC 4.3.5:
5666 // [...] nontrivally ownership-qualified types are [...] not trivially
5667 // default constructible, copy constructible, move constructible, copy
5668 // assignable, move assignable, or destructible [...]
5669 if (S.getLangOpts().ObjCAutoRefCount &&
5670 FieldType.hasNonTrivialObjCLifetime()) {
5671 if (Diagnose)
5672 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5673 << RD << FieldType.getObjCLifetime();
5674 return false;
5675 }
5676
Richard Smith41c35d62013-11-27 03:39:20 +00005677 bool ConstRHS = ConstArg && !FI->isMutable();
5678 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5679 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005680 return false;
5681 }
5682
5683 return true;
5684}
5685
5686/// Diagnose why the specified class does not have a trivial special member of
5687/// the given kind.
5688void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5689 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005690
Richard Smith41c35d62013-11-27 03:39:20 +00005691 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5692 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005693 TSK_CompleteObject, /*Diagnose*/true);
5694}
5695
5696/// Determine whether a defaulted or deleted special member function is trivial,
5697/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5698/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5699bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5700 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005701 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5702
5703 CXXRecordDecl *RD = MD->getParent();
5704
5705 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005706
Richard Smith2002bfe2013-11-04 02:02:27 +00005707 // C++11 [class.copy]p12, p25: [DR1593]
5708 // A [special member] is trivial if [...] its parameter-type-list is
5709 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005710 switch (CSM) {
5711 case CXXDefaultConstructor:
5712 case CXXDestructor:
5713 // Trivial default constructors and destructors cannot have parameters.
5714 break;
5715
5716 case CXXCopyConstructor:
5717 case CXXCopyAssignment: {
5718 // Trivial copy operations always have const, non-volatile parameter types.
5719 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005720 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005721 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5722 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5723 if (Diagnose)
5724 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5725 << Param0->getSourceRange() << Param0->getType()
5726 << Context.getLValueReferenceType(
5727 Context.getRecordType(RD).withConst());
5728 return false;
5729 }
5730 break;
5731 }
5732
5733 case CXXMoveConstructor:
5734 case CXXMoveAssignment: {
5735 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005736 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005737 const RValueReferenceType *RT =
5738 Param0->getType()->getAs<RValueReferenceType>();
5739 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5740 if (Diagnose)
5741 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5742 << Param0->getSourceRange() << Param0->getType()
5743 << Context.getRValueReferenceType(Context.getRecordType(RD));
5744 return false;
5745 }
5746 break;
5747 }
5748
5749 case CXXInvalid:
5750 llvm_unreachable("not a special member");
5751 }
5752
Richard Smith92f241f2012-12-08 02:53:02 +00005753 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5754 if (Diagnose)
5755 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5756 diag::note_nontrivial_default_arg)
5757 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5758 return false;
5759 }
5760 if (MD->isVariadic()) {
5761 if (Diagnose)
5762 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5763 return false;
5764 }
5765
5766 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5767 // A copy/move [constructor or assignment operator] is trivial if
5768 // -- the [member] selected to copy/move each direct base class subobject
5769 // is trivial
5770 //
5771 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5772 // A [default constructor or destructor] is trivial if
5773 // -- all the direct base classes have trivial [default constructors or
5774 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005775 for (const auto &BI : RD->bases())
5776 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005777 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005778 return false;
5779
5780 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5781 // A copy/move [constructor or assignment operator] for a class X is
5782 // trivial if
5783 // -- for each non-static data member of X that is of class type (or array
5784 // thereof), the constructor selected to copy/move that member is
5785 // trivial
5786 //
5787 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5788 // A [default constructor or destructor] is trivial if
5789 // -- for all of the non-static data members of its class that are of class
5790 // type (or array thereof), each such class has a trivial [default
5791 // constructor or destructor]
5792 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5793 return false;
5794
5795 // C++11 [class.dtor]p5:
5796 // A destructor is trivial if [...]
5797 // -- the destructor is not virtual
5798 if (CSM == CXXDestructor && MD->isVirtual()) {
5799 if (Diagnose)
5800 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5801 return false;
5802 }
5803
5804 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5805 // A [special member] for class X is trivial if [...]
5806 // -- class X has no virtual functions and no virtual base classes
5807 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5808 if (!Diagnose)
5809 return false;
5810
5811 if (RD->getNumVBases()) {
5812 // Check for virtual bases. We already know that the corresponding
5813 // member in all bases is trivial, so vbases must all be direct.
5814 CXXBaseSpecifier &BS = *RD->vbases_begin();
5815 assert(BS.isVirtual());
5816 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5817 return false;
5818 }
5819
5820 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005821 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005822 if (MI->isVirtual()) {
5823 SourceLocation MLoc = MI->getLocStart();
5824 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5825 return false;
5826 }
5827 }
5828
5829 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5830 }
5831
5832 // Looks like it's trivial!
5833 return true;
5834}
5835
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005836/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005837namespace {
5838 struct FindHiddenVirtualMethodData {
5839 Sema *S;
5840 CXXMethodDecl *Method;
5841 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005842 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005843 };
5844}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005845
David Blaikie282c92a2012-10-19 00:53:08 +00005846/// \brief Check whether any most overriden method from MD in Methods
5847static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5848 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5849 if (MD->size_overridden_methods() == 0)
5850 return Methods.count(MD->getCanonicalDecl());
5851 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5852 E = MD->end_overridden_methods();
5853 I != E; ++I)
5854 if (CheckMostOverridenMethods(*I, Methods))
5855 return true;
5856 return false;
5857}
5858
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005859/// \brief Member lookup function that determines whether a given C++
5860/// method overloads virtual methods in a base class without overriding any,
5861/// to be used with CXXRecordDecl::lookupInBases().
5862static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5863 CXXBasePath &Path,
5864 void *UserData) {
5865 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5866
5867 FindHiddenVirtualMethodData &Data
5868 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5869
5870 DeclarationName Name = Data.Method->getDeclName();
5871 assert(Name.getNameKind() == DeclarationName::Identifier);
5872
5873 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005874 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005875 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005876 !Path.Decls.empty();
5877 Path.Decls = Path.Decls.slice(1)) {
5878 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005879 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005880 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005881 foundSameNameMethod = true;
5882 // Interested only in hidden virtual methods.
5883 if (!MD->isVirtual())
5884 continue;
5885 // If the method we are checking overrides a method from its base
5886 // don't warn about the other overloaded methods.
5887 if (!Data.S->IsOverload(Data.Method, MD, false))
5888 return true;
5889 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005890 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005891 overloadedMethods.push_back(MD);
5892 }
5893 }
5894
5895 if (foundSameNameMethod)
5896 Data.OverloadedMethods.append(overloadedMethods.begin(),
5897 overloadedMethods.end());
5898 return foundSameNameMethod;
5899}
5900
David Blaikie282c92a2012-10-19 00:53:08 +00005901/// \brief Add the most overriden methods from MD to Methods
5902static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5903 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5904 if (MD->size_overridden_methods() == 0)
5905 Methods.insert(MD->getCanonicalDecl());
5906 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5907 E = MD->end_overridden_methods();
5908 I != E; ++I)
5909 AddMostOverridenMethods(*I, Methods);
5910}
5911
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005912/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005913/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005914void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5915 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005916 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005917 return;
5918
5919 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5920 /*bool RecordPaths=*/false,
5921 /*bool DetectVirtual=*/false);
5922 FindHiddenVirtualMethodData Data;
5923 Data.Method = MD;
5924 Data.S = this;
5925
5926 // Keep the base methods that were overriden or introduced in the subclass
5927 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005928 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005929 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5930 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5931 NamedDecl *ND = *I;
5932 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005933 ND = shad->getTargetDecl();
5934 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5935 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005936 }
5937
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005938 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5939 OverloadedMethods = Data.OverloadedMethods;
5940}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005941
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005942void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5943 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5944 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5945 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5946 PartialDiagnostic PD = PDiag(
5947 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5948 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5949 Diag(overloadedMD->getLocation(), PD);
5950 }
5951}
5952
5953/// \brief Diagnose methods which overload virtual methods in a base class
5954/// without overriding any.
5955void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5956 if (MD->isInvalidDecl())
5957 return;
5958
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005959 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005960 return;
5961
5962 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5963 FindHiddenVirtualMethods(MD, OverloadedMethods);
5964 if (!OverloadedMethods.empty()) {
5965 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5966 << MD << (OverloadedMethods.size() > 1);
5967
5968 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005969 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005970}
5971
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005972void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005973 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005974 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005975 SourceLocation RBrac,
5976 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005977 if (!TagDecl)
5978 return;
Mike Stump11289f42009-09-09 15:08:12 +00005979
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005980 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005981
Rafael Espindola06e1b132012-07-12 04:32:30 +00005982 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5983 if (l->getKind() != AttributeList::AT_Visibility)
5984 continue;
5985 l->setInvalid();
5986 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5987 l->getName();
5988 }
5989
David Blaikie751c5582011-09-22 02:58:26 +00005990 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005991 // strict aliasing violation!
5992 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005993 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005994
Douglas Gregor0be31a22010-07-02 17:43:08 +00005995 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005996 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005997}
5998
Douglas Gregor05379422008-11-03 17:51:48 +00005999/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6000/// special functions, such as the default constructor, copy
6001/// constructor, or destructor, to the given C++ class (C++
6002/// [special]p1). This routine can only be executed just before the
6003/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006004void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006005 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006006 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006007
Richard Smith6b02d462012-12-08 08:32:28 +00006008 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006009 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006010
Richard Smith6b02d462012-12-08 08:32:28 +00006011 // If the properties or semantics of the copy constructor couldn't be
6012 // determined while the class was being declared, force a declaration
6013 // of it now.
6014 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6015 DeclareImplicitCopyConstructor(ClassDecl);
6016 }
6017
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006018 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006019 ++ASTContext::NumImplicitMoveConstructors;
6020
Richard Smith6b02d462012-12-08 08:32:28 +00006021 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6022 DeclareImplicitMoveConstructor(ClassDecl);
6023 }
6024
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006025 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6026 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006027
6028 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006029 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006030 // it shows up in the right place in the vtable and that we diagnose
6031 // problems with the implicit exception specification.
6032 if (ClassDecl->isDynamicClass() ||
6033 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006034 DeclareImplicitCopyAssignment(ClassDecl);
6035 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006036
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006037 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006038 ++ASTContext::NumImplicitMoveAssignmentOperators;
6039
6040 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006041 if (ClassDecl->isDynamicClass() ||
6042 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006043 DeclareImplicitMoveAssignment(ClassDecl);
6044 }
6045
Douglas Gregor7454c562010-07-02 20:37:36 +00006046 if (!ClassDecl->hasUserDeclaredDestructor()) {
6047 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006048
6049 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006050 // have to declare the destructor immediately. This ensures that, e.g., it
6051 // shows up in the right place in the vtable and that we diagnose problems
6052 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006053 if (ClassDecl->isDynamicClass() ||
6054 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006055 DeclareImplicitDestructor(ClassDecl);
6056 }
Douglas Gregor05379422008-11-03 17:51:48 +00006057}
6058
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006059unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006060 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006061 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006062
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006063 // The order of template parameters is not important here. All names
6064 // get added to the same scope.
6065 SmallVector<TemplateParameterList *, 4> ParameterLists;
6066
6067 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6068 D = TD->getTemplatedDecl();
6069
6070 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6071 ParameterLists.push_back(PSD->getTemplateParameters());
6072
6073 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6074 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6075 ParameterLists.push_back(DD->getTemplateParameterList(i));
6076
6077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6078 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6079 ParameterLists.push_back(FTD->getTemplateParameters());
6080 }
6081 }
6082
6083 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6084 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6085 ParameterLists.push_back(TD->getTemplateParameterList(i));
6086
6087 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6088 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6089 ParameterLists.push_back(CTD->getTemplateParameters());
6090 }
6091 }
6092
6093 unsigned Count = 0;
6094 for (TemplateParameterList *Params : ParameterLists) {
6095 if (Params->size() > 0)
6096 // Ignore explicit specializations; they don't contribute to the template
6097 // depth.
6098 ++Count;
6099 for (NamedDecl *Param : *Params) {
6100 if (Param->getDeclName()) {
6101 S->AddDecl(Param);
6102 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006103 }
6104 }
6105 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006106
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006107 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006108}
6109
John McCall48871652010-08-21 09:40:31 +00006110void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006111 if (!RecordD) return;
6112 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006113 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006114 PushDeclContext(S, Record);
6115}
6116
John McCall48871652010-08-21 09:40:31 +00006117void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006118 if (!RecordD) return;
6119 PopDeclContext();
6120}
6121
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006122/// This is used to implement the constant expression evaluation part of the
6123/// attribute enable_if extension. There is nothing in standard C++ which would
6124/// require reentering parameters.
6125void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6126 if (!Param)
6127 return;
6128
6129 S->AddDecl(Param);
6130 if (Param->getDeclName())
6131 IdResolver.AddDecl(Param);
6132}
6133
Douglas Gregor4d87df52008-12-16 21:30:33 +00006134/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6135/// parsing a top-level (non-nested) C++ class, and we are now
6136/// parsing those parts of the given Method declaration that could
6137/// not be parsed earlier (C++ [class.mem]p2), such as default
6138/// arguments. This action should enter the scope of the given
6139/// Method declaration as if we had just parsed the qualified method
6140/// name. However, it should not bring the parameters into scope;
6141/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006142void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006143}
6144
6145/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6146/// C++ method declaration. We're (re-)introducing the given
6147/// function parameter into scope for use in parsing later parts of
6148/// the method declaration. For example, we could see an
6149/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006150void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006151 if (!ParamD)
6152 return;
Mike Stump11289f42009-09-09 15:08:12 +00006153
John McCall48871652010-08-21 09:40:31 +00006154 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006155
6156 // If this parameter has an unparsed default argument, clear it out
6157 // to make way for the parsed default argument.
6158 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006159 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006160
John McCall48871652010-08-21 09:40:31 +00006161 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006162 if (Param->getDeclName())
6163 IdResolver.AddDecl(Param);
6164}
6165
6166/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6167/// processing the delayed method declaration for Method. The method
6168/// declaration is now considered finished. There may be a separate
6169/// ActOnStartOfFunctionDef action later (not necessarily
6170/// immediately!) for this method, if it was also defined inside the
6171/// class body.
John McCall48871652010-08-21 09:40:31 +00006172void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006173 if (!MethodD)
6174 return;
Mike Stump11289f42009-09-09 15:08:12 +00006175
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006176 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006177
John McCall48871652010-08-21 09:40:31 +00006178 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006179
6180 // Now that we have our default arguments, check the constructor
6181 // again. It could produce additional diagnostics or affect whether
6182 // the class has implicitly-declared destructors, among other
6183 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006184 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6185 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006186
6187 // Check the default arguments, which we may have added.
6188 if (!Method->isInvalidDecl())
6189 CheckCXXDefaultArguments(Method);
6190}
6191
Douglas Gregor831c93f2008-11-05 20:51:48 +00006192/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006193/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006194/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006195/// emit diagnostics and set the invalid bit to true. In any case, the type
6196/// will be updated to reflect a well-formed type for the constructor and
6197/// returned.
6198QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006199 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006200 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006201
6202 // C++ [class.ctor]p3:
6203 // A constructor shall not be virtual (10.3) or static (9.4). A
6204 // constructor can be invoked for a const, volatile or const
6205 // volatile object. A constructor shall not be declared const,
6206 // volatile, or const volatile (9.3.2).
6207 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006208 if (!D.isInvalidType())
6209 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6210 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6211 << SourceRange(D.getIdentifierLoc());
6212 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006213 }
John McCall8e7d6562010-08-26 03:08:43 +00006214 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006215 if (!D.isInvalidType())
6216 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6217 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6218 << SourceRange(D.getIdentifierLoc());
6219 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006220 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006221 }
Mike Stump11289f42009-09-09 15:08:12 +00006222
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006223 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006224 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006225 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006226 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6227 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006228 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006229 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6230 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006231 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006232 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6233 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006234 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006235 }
Mike Stump11289f42009-09-09 15:08:12 +00006236
Douglas Gregordb9d6642011-01-26 05:01:58 +00006237 // C++0x [class.ctor]p4:
6238 // A constructor shall not be declared with a ref-qualifier.
6239 if (FTI.hasRefQualifier()) {
6240 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6241 << FTI.RefQualifierIsLValueRef
6242 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6243 D.setInvalidType();
6244 }
6245
Douglas Gregor831c93f2008-11-05 20:51:48 +00006246 // Rebuild the function type "R" without any type qualifiers (in
6247 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006248 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006249 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006250 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006251 return R;
6252
6253 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6254 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006255 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006256
6257 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006258}
6259
Douglas Gregor4d87df52008-12-16 21:30:33 +00006260/// CheckConstructor - Checks a fully-formed constructor for
6261/// well-formedness, issuing any diagnostics required. Returns true if
6262/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006263void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006264 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006265 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6266 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006267 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006268
6269 // C++ [class.copy]p3:
6270 // A declaration of a constructor for a class X is ill-formed if
6271 // its first parameter is of type (optionally cv-qualified) X and
6272 // either there are no other parameters or else all other
6273 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006274 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006275 ((Constructor->getNumParams() == 1) ||
6276 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006277 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6278 Constructor->getTemplateSpecializationKind()
6279 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006280 QualType ParamType = Constructor->getParamDecl(0)->getType();
6281 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6282 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006283 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006284 const char *ConstRef
6285 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6286 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006287 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006288 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006289
6290 // FIXME: Rather that making the constructor invalid, we should endeavor
6291 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006292 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006293 }
6294 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006295}
6296
John McCalldeb646e2010-08-04 01:04:25 +00006297/// CheckDestructor - Checks a fully-formed destructor definition for
6298/// well-formedness, issuing any diagnostics required. Returns true
6299/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006300bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006301 CXXRecordDecl *RD = Destructor->getParent();
6302
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006303 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006304 SourceLocation Loc;
6305
6306 if (!Destructor->isImplicit())
6307 Loc = Destructor->getLocation();
6308 else
6309 Loc = RD->getLocation();
6310
6311 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006312 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006313 DeclarationName Name =
6314 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006315 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006316 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006317 // If there's no class-specific operator delete, look up the global
6318 // non-array delete.
6319 if (!OperatorDelete)
6320 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006321
Eli Friedmanfa0df832012-02-02 03:46:19 +00006322 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006323
6324 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006325 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006326
6327 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006328}
6329
Douglas Gregor831c93f2008-11-05 20:51:48 +00006330/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6331/// the well-formednes of the destructor declarator @p D with type @p
6332/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006333/// emit diagnostics and set the declarator to invalid. Even if this happens,
6334/// will be updated to reflect a well-formed type for the destructor and
6335/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006336QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006337 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006338 // C++ [class.dtor]p1:
6339 // [...] A typedef-name that names a class is a class-name
6340 // (7.1.3); however, a typedef-name that names a class shall not
6341 // be used as the identifier in the declarator for a destructor
6342 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006343 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006344 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006345 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006346 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006347 else if (const TemplateSpecializationType *TST =
6348 DeclaratorType->getAs<TemplateSpecializationType>())
6349 if (TST->isTypeAlias())
6350 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6351 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006352
6353 // C++ [class.dtor]p2:
6354 // A destructor is used to destroy objects of its class type. A
6355 // destructor takes no parameters, and no return type can be
6356 // specified for it (not even void). The address of a destructor
6357 // shall not be taken. A destructor shall not be static. A
6358 // destructor can be invoked for a const, volatile or const
6359 // volatile object. A destructor shall not be declared const,
6360 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006361 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006362 if (!D.isInvalidType())
6363 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6364 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006365 << SourceRange(D.getIdentifierLoc())
6366 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6367
John McCall8e7d6562010-08-26 03:08:43 +00006368 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006369 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006370 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006371 // Destructors don't have return types, but the parser will
6372 // happily parse something like:
6373 //
6374 // class X {
6375 // float ~X();
6376 // };
6377 //
6378 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006379 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6380 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6381 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006382 }
Mike Stump11289f42009-09-09 15:08:12 +00006383
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006384 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006385 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006386 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006387 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6388 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006389 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006390 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6391 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006392 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006393 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6394 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006395 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006396 }
6397
Douglas Gregordb9d6642011-01-26 05:01:58 +00006398 // C++0x [class.dtor]p2:
6399 // A destructor shall not be declared with a ref-qualifier.
6400 if (FTI.hasRefQualifier()) {
6401 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6402 << FTI.RefQualifierIsLValueRef
6403 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6404 D.setInvalidType();
6405 }
6406
Douglas Gregor831c93f2008-11-05 20:51:48 +00006407 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006408 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006409 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6410
6411 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006412 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006413 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006414 }
6415
Mike Stump11289f42009-09-09 15:08:12 +00006416 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006417 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006418 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006419 D.setInvalidType();
6420 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006421
6422 // Rebuild the function type "R" without any type qualifiers or
6423 // parameters (in case any of the errors above fired) and with
6424 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006425 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006426 if (!D.isInvalidType())
6427 return R;
6428
Douglas Gregor95755162010-07-01 05:10:53 +00006429 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006430 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6431 EPI.Variadic = false;
6432 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006433 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006434 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006435}
6436
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006437/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6438/// well-formednes of the conversion function declarator @p D with
6439/// type @p R. If there are any errors in the declarator, this routine
6440/// will emit diagnostics and return true. Otherwise, it will return
6441/// false. Either way, the type @p R will be updated to reflect a
6442/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006443void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006444 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006445 // C++ [class.conv.fct]p1:
6446 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006447 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006448 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006449 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006450 if (!D.isInvalidType())
6451 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006452 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6453 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006454 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006455 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006456 }
John McCall212fa2e2010-04-13 00:04:31 +00006457
6458 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6459
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006460 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006461 // Conversion functions don't have return types, but the parser will
6462 // happily parse something like:
6463 //
6464 // class X {
6465 // float operator bool();
6466 // };
6467 //
6468 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006469 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6470 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6471 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006472 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006473 }
6474
John McCall212fa2e2010-04-13 00:04:31 +00006475 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6476
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006477 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006478 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006479 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6480
6481 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006482 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006483 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006484 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006485 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006486 D.setInvalidType();
6487 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006488
John McCall212fa2e2010-04-13 00:04:31 +00006489 // Diagnose "&operator bool()" and other such nonsense. This
6490 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006491 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006492 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006493 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006494 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006495 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006496 }
6497
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006498 // C++ [class.conv.fct]p4:
6499 // The conversion-type-id shall not represent a function type nor
6500 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006501 if (ConvType->isArrayType()) {
6502 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6503 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006504 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006505 } else if (ConvType->isFunctionType()) {
6506 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6507 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006508 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006509 }
6510
6511 // Rebuild the function type "R" without any parameters (in case any
6512 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006513 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006514 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006515 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006516
Douglas Gregor5fb53972009-01-14 15:45:31 +00006517 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006518 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006519 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006520 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006521 diag::warn_cxx98_compat_explicit_conversion_functions :
6522 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006523 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006524}
6525
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006526/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6527/// the declaration of the given C++ conversion function. This routine
6528/// is responsible for recording the conversion function in the C++
6529/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006530Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006531 assert(Conversion && "Expected to receive a conversion function declaration");
6532
Douglas Gregor4287b372008-12-12 08:25:50 +00006533 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006534
6535 // Make sure we aren't redeclaring the conversion function.
6536 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006537
6538 // C++ [class.conv.fct]p1:
6539 // [...] A conversion function is never used to convert a
6540 // (possibly cv-qualified) object to the (possibly cv-qualified)
6541 // same object type (or a reference to it), to a (possibly
6542 // cv-qualified) base class of that type (or a reference to it),
6543 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006544 // FIXME: Suppress this warning if the conversion function ends up being a
6545 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006546 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006547 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006548 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006549 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006550 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6551 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006552 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006553 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006554 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6555 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006556 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006557 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006558 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006559 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006560 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006561 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006562 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006563 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006564 }
6565
Douglas Gregor457104e2010-09-29 04:25:11 +00006566 if (FunctionTemplateDecl *ConversionTemplate
6567 = Conversion->getDescribedFunctionTemplate())
6568 return ConversionTemplate;
6569
John McCall48871652010-08-21 09:40:31 +00006570 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006571}
6572
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006573//===----------------------------------------------------------------------===//
6574// Namespace Handling
6575//===----------------------------------------------------------------------===//
6576
Richard Smith45bb8852012-10-04 22:13:39 +00006577/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6578/// reopened.
6579static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6580 SourceLocation Loc,
6581 IdentifierInfo *II, bool *IsInline,
6582 NamespaceDecl *PrevNS) {
6583 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006584
Richard Smithf501cc32012-10-05 01:46:25 +00006585 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6586 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6587 // inline namespaces, with the intention of bringing names into namespace std.
6588 //
6589 // We support this just well enough to get that case working; this is not
6590 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006591 if (*IsInline && II && II->getName().startswith("__atomic") &&
6592 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006593 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006594 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6595 NS = NS->getPreviousDecl())
6596 NS->setInline(*IsInline);
6597 // Patch up the lookup table for the containing namespace. This isn't really
6598 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006599 for (auto *I : PrevNS->decls())
6600 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006601 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6602 return;
6603 }
6604
6605 if (PrevNS->isInline())
6606 // The user probably just forgot the 'inline', so suggest that it
6607 // be added back.
6608 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6609 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6610 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006611 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006612
6613 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6614 *IsInline = PrevNS->isInline();
6615}
John McCallb1be5232010-08-26 09:15:37 +00006616
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006617/// ActOnStartNamespaceDef - This is called at the start of a namespace
6618/// definition.
John McCall48871652010-08-21 09:40:31 +00006619Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006620 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006621 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006622 SourceLocation IdentLoc,
6623 IdentifierInfo *II,
6624 SourceLocation LBrace,
6625 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006626 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6627 // For anonymous namespace, take the location of the left brace.
6628 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006629 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006630 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006631 bool IsStd = false;
6632 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006633 Scope *DeclRegionScope = NamespcScope->getParent();
6634
Craig Topperc3ec1492014-05-26 06:22:03 +00006635 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006636 if (II) {
6637 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006638 // The identifier in an original-namespace-definition shall not
6639 // have been previously defined in the declarative region in
6640 // which the original-namespace-definition appears. The
6641 // identifier in an original-namespace-definition is the name of
6642 // the namespace. Subsequently in that declarative region, it is
6643 // treated as an original-namespace-name.
6644 //
6645 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006646 // look through using directives, just look for any ordinary names.
6647
6648 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006649 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6650 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006651 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006652 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6653 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6654 ++I) {
6655 if ((*I)->getIdentifierNamespace() & IDNS) {
6656 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006657 break;
6658 }
6659 }
6660
Douglas Gregore57e7522012-01-07 09:11:48 +00006661 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6662
6663 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006664 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006665 if (IsInline != PrevNS->isInline())
6666 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6667 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006668 } else if (PrevDecl) {
6669 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006670 Diag(Loc, diag::err_redefinition_different_kind)
6671 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006672 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006673 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006674 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006675 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006676 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006677 // This is the first "real" definition of the namespace "std", so update
6678 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006679 PrevNS = getStdNamespace();
6680 IsStd = true;
6681 AddToKnown = !IsInline;
6682 } else {
6683 // We've seen this namespace for the first time.
6684 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006685 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006686 } else {
John McCall4fa53422009-10-01 00:25:31 +00006687 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006688
6689 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006690 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006691 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006692 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006693 } else {
6694 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006695 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006696 }
6697
Richard Smith45bb8852012-10-04 22:13:39 +00006698 if (PrevNS && IsInline != PrevNS->isInline())
6699 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6700 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006701 }
6702
6703 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6704 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006705 if (IsInvalid)
6706 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006707
6708 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006709
Douglas Gregore57e7522012-01-07 09:11:48 +00006710 // FIXME: Should we be merging attributes?
6711 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006712 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006713
6714 if (IsStd)
6715 StdNamespace = Namespc;
6716 if (AddToKnown)
6717 KnownNamespaces[Namespc] = false;
6718
6719 if (II) {
6720 PushOnScopeChains(Namespc, DeclRegionScope);
6721 } else {
6722 // Link the anonymous namespace into its parent.
6723 DeclContext *Parent = CurContext->getRedeclContext();
6724 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6725 TU->setAnonymousNamespace(Namespc);
6726 } else {
6727 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006728 }
John McCall4fa53422009-10-01 00:25:31 +00006729
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006730 CurContext->addDecl(Namespc);
6731
John McCall4fa53422009-10-01 00:25:31 +00006732 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6733 // behaves as if it were replaced by
6734 // namespace unique { /* empty body */ }
6735 // using namespace unique;
6736 // namespace unique { namespace-body }
6737 // where all occurrences of 'unique' in a translation unit are
6738 // replaced by the same identifier and this identifier differs
6739 // from all other identifiers in the entire program.
6740
6741 // We just create the namespace with an empty name and then add an
6742 // implicit using declaration, just like the standard suggests.
6743 //
6744 // CodeGen enforces the "universally unique" aspect by giving all
6745 // declarations semantically contained within an anonymous
6746 // namespace internal linkage.
6747
Douglas Gregore57e7522012-01-07 09:11:48 +00006748 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006749 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006750 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006751 /* 'using' */ LBrace,
6752 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006753 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006754 /* identifier */ SourceLocation(),
6755 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006756 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006757 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006758 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006759 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006760 }
6761
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006762 ActOnDocumentableDecl(Namespc);
6763
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006764 // Although we could have an invalid decl (i.e. the namespace name is a
6765 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006766 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6767 // for the namespace has the declarations that showed up in that particular
6768 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006769 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006770 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006771}
6772
Sebastian Redla6602e92009-11-23 15:34:23 +00006773/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6774/// is a namespace alias, returns the namespace it points to.
6775static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6776 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6777 return AD->getNamespace();
6778 return dyn_cast_or_null<NamespaceDecl>(D);
6779}
6780
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006781/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6782/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006783void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006784 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6785 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006786 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006787 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006788 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006789 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006790}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006791
John McCall28a0cf72010-08-25 07:42:41 +00006792CXXRecordDecl *Sema::getStdBadAlloc() const {
6793 return cast_or_null<CXXRecordDecl>(
6794 StdBadAlloc.get(Context.getExternalSource()));
6795}
6796
6797NamespaceDecl *Sema::getStdNamespace() const {
6798 return cast_or_null<NamespaceDecl>(
6799 StdNamespace.get(Context.getExternalSource()));
6800}
6801
Douglas Gregorcdf87022010-06-29 17:53:46 +00006802/// \brief Retrieve the special "std" namespace, which may require us to
6803/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006804NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006805 if (!StdNamespace) {
6806 // The "std" namespace has not yet been defined, so build one implicitly.
6807 StdNamespace = NamespaceDecl::Create(Context,
6808 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006809 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006810 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006811 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00006812 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006813 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006814 }
6815
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006816 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006817}
6818
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006819bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006820 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006821 "Looking for std::initializer_list outside of C++.");
6822
6823 // We're looking for implicit instantiations of
6824 // template <typename E> class std::initializer_list.
6825
6826 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6827 return false;
6828
Craig Topperc3ec1492014-05-26 06:22:03 +00006829 ClassTemplateDecl *Template = nullptr;
6830 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006831
Sebastian Redl43144e72012-01-17 22:49:58 +00006832 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006833
Sebastian Redl43144e72012-01-17 22:49:58 +00006834 ClassTemplateSpecializationDecl *Specialization =
6835 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6836 if (!Specialization)
6837 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006838
Sebastian Redl43144e72012-01-17 22:49:58 +00006839 Template = Specialization->getSpecializedTemplate();
6840 Arguments = Specialization->getTemplateArgs().data();
6841 } else if (const TemplateSpecializationType *TST =
6842 Ty->getAs<TemplateSpecializationType>()) {
6843 Template = dyn_cast_or_null<ClassTemplateDecl>(
6844 TST->getTemplateName().getAsTemplateDecl());
6845 Arguments = TST->getArgs();
6846 }
6847 if (!Template)
6848 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006849
6850 if (!StdInitializerList) {
6851 // Haven't recognized std::initializer_list yet, maybe this is it.
6852 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6853 if (TemplateClass->getIdentifier() !=
6854 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006855 !getStdNamespace()->InEnclosingNamespaceSetOf(
6856 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006857 return false;
6858 // This is a template called std::initializer_list, but is it the right
6859 // template?
6860 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006861 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006862 return false;
6863 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6864 return false;
6865
6866 // It's the right template.
6867 StdInitializerList = Template;
6868 }
6869
6870 if (Template != StdInitializerList)
6871 return false;
6872
6873 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006874 if (Element)
6875 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006876 return true;
6877}
6878
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006879static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6880 NamespaceDecl *Std = S.getStdNamespace();
6881 if (!Std) {
6882 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006883 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006884 }
6885
6886 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6887 Loc, Sema::LookupOrdinaryName);
6888 if (!S.LookupQualifiedName(Result, Std)) {
6889 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006890 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006891 }
6892 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6893 if (!Template) {
6894 Result.suppressDiagnostics();
6895 // We found something weird. Complain about the first thing we found.
6896 NamedDecl *Found = *Result.begin();
6897 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00006898 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006899 }
6900
6901 // We found some template called std::initializer_list. Now verify that it's
6902 // correct.
6903 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006904 if (Params->getMinRequiredArguments() != 1 ||
6905 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006906 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00006907 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006908 }
6909
6910 return Template;
6911}
6912
6913QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6914 if (!StdInitializerList) {
6915 StdInitializerList = LookupStdInitializerList(*this, Loc);
6916 if (!StdInitializerList)
6917 return QualType();
6918 }
6919
6920 TemplateArgumentListInfo Args(Loc, Loc);
6921 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6922 Context.getTrivialTypeSourceInfo(Element,
6923 Loc)));
6924 return Context.getCanonicalType(
6925 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6926}
6927
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006928bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6929 // C++ [dcl.init.list]p2:
6930 // A constructor is an initializer-list constructor if its first parameter
6931 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6932 // std::initializer_list<E> for some type E, and either there are no other
6933 // parameters or else all other parameters have default arguments.
6934 if (Ctor->getNumParams() < 1 ||
6935 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6936 return false;
6937
6938 QualType ArgType = Ctor->getParamDecl(0)->getType();
6939 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6940 ArgType = RT->getPointeeType().getUnqualifiedType();
6941
Craig Topperc3ec1492014-05-26 06:22:03 +00006942 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006943}
6944
Douglas Gregora172e082011-03-26 22:25:30 +00006945/// \brief Determine whether a using statement is in a context where it will be
6946/// apply in all contexts.
6947static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6948 switch (CurContext->getDeclKind()) {
6949 case Decl::TranslationUnit:
6950 return true;
6951 case Decl::LinkageSpec:
6952 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6953 default:
6954 return false;
6955 }
6956}
6957
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006958namespace {
6959
6960// Callback to only accept typo corrections that are namespaces.
6961class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006962public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006963 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006964 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006965 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006966 return false;
6967 }
6968};
6969
6970}
6971
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006972static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6973 CXXScopeSpec &SS,
6974 SourceLocation IdentLoc,
6975 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006976 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006977 R.clear();
6978 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006979 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00006980 Validator,
6981 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006982 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006983 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6984 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006985 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006986 S.diagnoseTypo(Corrected,
6987 S.PDiag(diag::err_using_directive_member_suggest)
6988 << Ident << DC << DroppedSpecifier << SS.getRange(),
6989 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006990 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006991 S.diagnoseTypo(Corrected,
6992 S.PDiag(diag::err_using_directive_suggest) << Ident,
6993 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006994 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006995 R.addDecl(Corrected.getCorrectionDecl());
6996 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006997 }
6998 return false;
6999}
7000
John McCall48871652010-08-21 09:40:31 +00007001Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007002 SourceLocation UsingLoc,
7003 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007004 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007005 SourceLocation IdentLoc,
7006 IdentifierInfo *NamespcName,
7007 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007008 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7009 assert(NamespcName && "Invalid NamespcName.");
7010 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007011
7012 // This can only happen along a recovery path.
7013 while (S->getFlags() & Scope::TemplateParamScope)
7014 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007015 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007016
Craig Topperc3ec1492014-05-26 06:22:03 +00007017 UsingDirectiveDecl *UDir = nullptr;
7018 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007019 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007020 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007021
Douglas Gregor34074322009-01-14 22:20:51 +00007022 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007023 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7024 LookupParsedName(R, S, &SS);
7025 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007026 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007027
Douglas Gregorcdf87022010-06-29 17:53:46 +00007028 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007029 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007030 // Allow "using namespace std;" or "using namespace ::std;" even if
7031 // "std" hasn't been defined yet, for GCC compatibility.
7032 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7033 NamespcName->isStr("std")) {
7034 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007035 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007036 R.resolveKind();
7037 }
7038 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007039 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007040 }
7041
John McCall9f3059a2009-10-09 21:13:30 +00007042 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007043 NamedDecl *Named = R.getFoundDecl();
7044 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7045 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007046 // C++ [namespace.udir]p1:
7047 // A using-directive specifies that the names in the nominated
7048 // namespace can be used in the scope in which the
7049 // using-directive appears after the using-directive. During
7050 // unqualified name lookup (3.4.1), the names appear as if they
7051 // were declared in the nearest enclosing namespace which
7052 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007053 // namespace. [Note: in this context, "contains" means "contains
7054 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007055
7056 // Find enclosing context containing both using-directive and
7057 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007058 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007059 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7060 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7061 CommonAncestor = CommonAncestor->getParent();
7062
Sebastian Redla6602e92009-11-23 15:34:23 +00007063 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007064 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007065 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007066
Douglas Gregora172e082011-03-26 22:25:30 +00007067 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007068 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007069 Diag(IdentLoc, diag::warn_using_directive_in_header);
7070 }
7071
Douglas Gregor889ceb72009-02-03 19:21:40 +00007072 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007073 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007074 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007075 }
7076
Richard Smith54ecd982013-02-20 19:22:51 +00007077 if (UDir)
7078 ProcessDeclAttributeList(S, UDir, AttrList);
7079
John McCall48871652010-08-21 09:40:31 +00007080 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007081}
7082
7083void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007084 // If the scope has an associated entity and the using directive is at
7085 // namespace or translation unit scope, add the UsingDirectiveDecl into
7086 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007087 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007088 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007089 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007090 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007091 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007092 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007093 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007094}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007095
Douglas Gregorfec52632009-06-20 00:51:54 +00007096
John McCall48871652010-08-21 09:40:31 +00007097Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007098 AccessSpecifier AS,
7099 bool HasUsingKeyword,
7100 SourceLocation UsingLoc,
7101 CXXScopeSpec &SS,
7102 UnqualifiedId &Name,
7103 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007104 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007105 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007106 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007107
Douglas Gregor220f4272009-11-04 16:30:06 +00007108 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007109 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007110 case UnqualifiedId::IK_Identifier:
7111 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007112 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007113 case UnqualifiedId::IK_ConversionFunctionId:
7114 break;
7115
7116 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007117 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007118 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007119 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007120 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007121 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007122 diag::err_using_decl_constructor)
7123 << SS.getRange();
7124
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007125 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007126
Craig Topperc3ec1492014-05-26 06:22:03 +00007127 return nullptr;
7128
Douglas Gregor220f4272009-11-04 16:30:06 +00007129 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007130 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007131 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007132 return nullptr;
7133
Douglas Gregor220f4272009-11-04 16:30:06 +00007134 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007135 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007136 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007137 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007138 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007139
7140 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7141 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007142 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007143 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007144
Richard Smithc2bc61b2013-03-18 21:12:30 +00007145 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007146 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007147 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007148 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7149 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007150 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007151 }
7152
Douglas Gregorc4356532010-12-16 00:46:58 +00007153 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7154 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007155 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007156
John McCall3f746822009-11-17 05:59:44 +00007157 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007158 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007159 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007160 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007161 if (UD)
7162 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007163
John McCall48871652010-08-21 09:40:31 +00007164 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007165}
7166
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007167/// \brief Determine whether a using declaration considers the given
7168/// declarations as "equivalent", e.g., if they are redeclarations of
7169/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007170static bool
7171IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7172 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007173 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007174
Richard Smithdda56e42011-04-15 14:24:37 +00007175 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007176 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007177 return Context.hasSameType(TD1->getUnderlyingType(),
7178 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007179
7180 return false;
7181}
7182
7183
John McCall84d87672009-12-10 09:41:52 +00007184/// Determines whether to create a using shadow decl for a particular
7185/// decl, given the set of decls existing prior to this using lookup.
7186bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007187 const LookupResult &Previous,
7188 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007189 // Diagnose finding a decl which is not from a base class of the
7190 // current class. We do this now because there are cases where this
7191 // function will silently decide not to build a shadow decl, which
7192 // will pre-empt further diagnostics.
7193 //
7194 // We don't need to do this in C++0x because we do the check once on
7195 // the qualifier.
7196 //
7197 // FIXME: diagnose the following if we care enough:
7198 // struct A { int foo; };
7199 // struct B : A { using A::foo; };
7200 // template <class T> struct C : A {};
7201 // template <class T> struct D : C<T> { using B::foo; } // <---
7202 // This is invalid (during instantiation) in C++03 because B::foo
7203 // resolves to the using decl in B, which is not a base class of D<T>.
7204 // We can't diagnose it immediately because C<T> is an unknown
7205 // specialization. The UsingShadowDecl in D<T> then points directly
7206 // to A::foo, which will look well-formed when we instantiate.
7207 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007208 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007209 DeclContext *OrigDC = Orig->getDeclContext();
7210
7211 // Handle enums and anonymous structs.
7212 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7213 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7214 while (OrigRec->isAnonymousStructOrUnion())
7215 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7216
7217 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7218 if (OrigDC == CurContext) {
7219 Diag(Using->getLocation(),
7220 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007221 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007222 Diag(Orig->getLocation(), diag::note_using_decl_target);
7223 return true;
7224 }
7225
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007226 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007227 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007228 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007229 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007230 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007231 Diag(Orig->getLocation(), diag::note_using_decl_target);
7232 return true;
7233 }
7234 }
7235
7236 if (Previous.empty()) return false;
7237
7238 NamedDecl *Target = Orig;
7239 if (isa<UsingShadowDecl>(Target))
7240 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7241
John McCalla17e83e2009-12-11 02:33:26 +00007242 // If the target happens to be one of the previous declarations, we
7243 // don't have a conflict.
7244 //
7245 // FIXME: but we might be increasing its access, in which case we
7246 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007247 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007248 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007249 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7250 I != E; ++I) {
7251 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007252 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7253 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7254 PrevShadow = Shadow;
7255 FoundEquivalentDecl = true;
7256 }
John McCalla17e83e2009-12-11 02:33:26 +00007257
7258 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7259 }
7260
Richard Smithfd8634a2013-10-23 02:17:46 +00007261 if (FoundEquivalentDecl)
7262 return false;
7263
Alp Tokera2794f92014-01-22 07:29:52 +00007264 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007265 NamedDecl *OldDecl = nullptr;
7266 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7267 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007268 case Ovl_Overload:
7269 return false;
7270
7271 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007272 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007273 break;
Richard Smith18819302014-02-06 01:31:33 +00007274
John McCall84d87672009-12-10 09:41:52 +00007275 // We found a decl with the exact signature.
7276 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007277 // If we're in a record, we want to hide the target, so we
7278 // return true (without a diagnostic) to tell the caller not to
7279 // build a shadow decl.
7280 if (CurContext->isRecord())
7281 return true;
7282
7283 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007284 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007285 break;
7286 }
7287
7288 Diag(Target->getLocation(), diag::note_using_decl_target);
7289 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7290 return true;
7291 }
7292
7293 // Target is not a function.
7294
John McCall84d87672009-12-10 09:41:52 +00007295 if (isa<TagDecl>(Target)) {
7296 // No conflict between a tag and a non-tag.
7297 if (!Tag) return false;
7298
John McCalle29c5cd2009-12-10 19:51:03 +00007299 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007300 Diag(Target->getLocation(), diag::note_using_decl_target);
7301 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7302 return true;
7303 }
7304
7305 // No conflict between a tag and a non-tag.
7306 if (!NonTag) return false;
7307
John McCalle29c5cd2009-12-10 19:51:03 +00007308 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007309 Diag(Target->getLocation(), diag::note_using_decl_target);
7310 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7311 return true;
7312}
7313
John McCall3f746822009-11-17 05:59:44 +00007314/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007315UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007316 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007317 NamedDecl *Orig,
7318 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007319
7320 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007321 NamedDecl *Target = Orig;
7322 if (isa<UsingShadowDecl>(Target)) {
7323 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7324 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007325 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007326
John McCall3f746822009-11-17 05:59:44 +00007327 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007328 = UsingShadowDecl::Create(Context, CurContext,
7329 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007330 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007331
Douglas Gregor457104e2010-09-29 04:25:11 +00007332 Shadow->setAccess(UD->getAccess());
7333 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7334 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007335
7336 Shadow->setPreviousDecl(PrevDecl);
7337
John McCall3f746822009-11-17 05:59:44 +00007338 if (S)
John McCall3969e302009-12-08 07:46:18 +00007339 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007340 else
John McCall3969e302009-12-08 07:46:18 +00007341 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007342
John McCall3969e302009-12-08 07:46:18 +00007343
John McCall84d87672009-12-10 09:41:52 +00007344 return Shadow;
7345}
John McCall3969e302009-12-08 07:46:18 +00007346
John McCall84d87672009-12-10 09:41:52 +00007347/// Hides a using shadow declaration. This is required by the current
7348/// using-decl implementation when a resolvable using declaration in a
7349/// class is followed by a declaration which would hide or override
7350/// one or more of the using decl's targets; for example:
7351///
7352/// struct Base { void foo(int); };
7353/// struct Derived : Base {
7354/// using Base::foo;
7355/// void foo(int);
7356/// };
7357///
7358/// The governing language is C++03 [namespace.udecl]p12:
7359///
7360/// When a using-declaration brings names from a base class into a
7361/// derived class scope, member functions in the derived class
7362/// override and/or hide member functions with the same name and
7363/// parameter types in a base class (rather than conflicting).
7364///
7365/// There are two ways to implement this:
7366/// (1) optimistically create shadow decls when they're not hidden
7367/// by existing declarations, or
7368/// (2) don't create any shadow decls (or at least don't make them
7369/// visible) until we've fully parsed/instantiated the class.
7370/// The problem with (1) is that we might have to retroactively remove
7371/// a shadow decl, which requires several O(n) operations because the
7372/// decl structures are (very reasonably) not designed for removal.
7373/// (2) avoids this but is very fiddly and phase-dependent.
7374void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007375 if (Shadow->getDeclName().getNameKind() ==
7376 DeclarationName::CXXConversionFunctionName)
7377 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7378
John McCall84d87672009-12-10 09:41:52 +00007379 // Remove it from the DeclContext...
7380 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007381
John McCall84d87672009-12-10 09:41:52 +00007382 // ...and the scope, if applicable...
7383 if (S) {
John McCall48871652010-08-21 09:40:31 +00007384 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007385 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007386 }
7387
John McCall84d87672009-12-10 09:41:52 +00007388 // ...and the using decl.
7389 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7390
7391 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007392 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007393}
7394
Richard Smith09d5b3a2014-05-01 00:35:04 +00007395/// Find the base specifier for a base class with the given type.
7396static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7397 QualType DesiredBase,
7398 bool &AnyDependentBases) {
7399 // Check whether the named type is a direct base class.
7400 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7401 for (auto &Base : Derived->bases()) {
7402 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7403 if (CanonicalDesiredBase == BaseType)
7404 return &Base;
7405 if (BaseType->isDependentType())
7406 AnyDependentBases = true;
7407 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007408 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007409}
7410
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007411namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007412class UsingValidatorCCC : public CorrectionCandidateCallback {
7413public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007414 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007415 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007416 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007417 IsInstantiation(IsInstantiation), OldNNS(NNS),
7418 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007419
Craig Toppera798a9d2014-03-02 09:32:10 +00007420 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007421 NamedDecl *ND = Candidate.getCorrectionDecl();
7422
7423 // Keywords are not valid here.
7424 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007425 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007426
7427 // Completely unqualified names are invalid for a 'using' declaration.
7428 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7429 return false;
7430
Richard Smith09d5b3a2014-05-01 00:35:04 +00007431 if (RequireMemberOf) {
7432 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7433 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7434 // No-one ever wants a using-declaration to name an injected-class-name
7435 // of a base class, unless they're declaring an inheriting constructor.
7436 ASTContext &Ctx = ND->getASTContext();
7437 if (!Ctx.getLangOpts().CPlusPlus11)
7438 return false;
7439 QualType FoundType = Ctx.getRecordType(FoundRecord);
7440
7441 // Check that the injected-class-name is named as a member of its own
7442 // type; we don't want to suggest 'using Derived::Base;', since that
7443 // means something else.
7444 NestedNameSpecifier *Specifier =
7445 Candidate.WillReplaceSpecifier()
7446 ? Candidate.getCorrectionSpecifier()
7447 : OldNNS;
7448 if (!Specifier->getAsType() ||
7449 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7450 return false;
7451
7452 // Check that this inheriting constructor declaration actually names a
7453 // direct base class of the current class.
7454 bool AnyDependentBases = false;
7455 if (!findDirectBaseWithType(RequireMemberOf,
7456 Ctx.getRecordType(FoundRecord),
7457 AnyDependentBases) &&
7458 !AnyDependentBases)
7459 return false;
7460 } else {
7461 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7462 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7463 return false;
7464
7465 // FIXME: Check that the base class member is accessible?
7466 }
7467 }
7468
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007469 if (isa<TypeDecl>(ND))
7470 return HasTypenameKeyword || !IsInstantiation;
7471
7472 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007473 }
7474
7475private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007476 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007477 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007478 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007479 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007480};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007481} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007482
John McCalle61f2ba2009-11-18 02:36:19 +00007483/// Builds a using declaration.
7484///
7485/// \param IsInstantiation - Whether this call arises from an
7486/// instantiation of an unresolved using declaration. We treat
7487/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007488NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7489 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007490 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007491 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007492 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007493 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007494 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007495 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007496 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007497 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007498 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007499
Anders Carlssonf038fc22009-08-28 05:49:21 +00007500 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007501
Anders Carlsson59140b32009-08-28 03:16:11 +00007502 if (SS.isEmpty()) {
7503 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007504 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007505 }
Mike Stump11289f42009-09-09 15:08:12 +00007506
John McCall84d87672009-12-10 09:41:52 +00007507 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007508 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007509 ForRedeclaration);
7510 Previous.setHideTags(false);
7511 if (S) {
7512 LookupName(Previous, S);
7513
7514 // It is really dumb that we have to do this.
7515 LookupResult::Filter F = Previous.makeFilter();
7516 while (F.hasNext()) {
7517 NamedDecl *D = F.next();
7518 if (!isDeclInScope(D, CurContext, S))
7519 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007520 // If we found a local extern declaration that's not ordinarily visible,
7521 // and this declaration is being added to a non-block scope, ignore it.
7522 // We're only checking for scope conflicts here, not also for violations
7523 // of the linkage rules.
7524 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7525 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7526 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007527 }
7528 F.done();
7529 } else {
7530 assert(IsInstantiation && "no scope in non-instantiation");
7531 assert(CurContext->isRecord() && "scope not record in instantiation");
7532 LookupQualifiedName(Previous, CurContext);
7533 }
7534
John McCall84d87672009-12-10 09:41:52 +00007535 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007536 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7537 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007538 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007539
7540 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007541 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007542 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007543
John McCall84c16cf2009-11-12 03:15:40 +00007544 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007545 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007546 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007547 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007548 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007549 // FIXME: not all declaration name kinds are legal here
7550 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7551 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007552 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007553 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007554 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007555 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7556 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007557 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007558 D->setAccess(AS);
7559 CurContext->addDecl(D);
7560 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007561 }
John McCallb96ec562009-12-04 22:46:56 +00007562
Richard Smith09d5b3a2014-05-01 00:35:04 +00007563 auto Build = [&](bool Invalid) {
7564 UsingDecl *UD =
7565 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7566 HasTypenameKeyword);
7567 UD->setAccess(AS);
7568 CurContext->addDecl(UD);
7569 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007570 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007571 };
7572 auto BuildInvalid = [&]{ return Build(true); };
7573 auto BuildValid = [&]{ return Build(false); };
7574
7575 if (RequireCompleteDeclContext(SS, LookupContext))
7576 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007577
Richard Smith23d55872012-04-02 01:30:27 +00007578 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007579 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007580 UsingDecl *UD = BuildValid();
7581 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007582 return UD;
7583 }
7584
7585 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007586
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007587 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007588
John McCall3969e302009-12-08 07:46:18 +00007589 // Unlike most lookups, we don't always want to hide tag
7590 // declarations: tag names are visible through the using declaration
7591 // even if hidden by ordinary names, *except* in a dependent context
7592 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007593 if (!IsInstantiation)
7594 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007595
John McCall5dadb652012-04-07 03:04:20 +00007596 // For the purposes of this lookup, we have a base object type
7597 // equal to that of the current context.
7598 if (CurContext->isRecord()) {
7599 R.setBaseObjectType(
7600 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7601 }
7602
John McCall27b18f82009-11-17 02:14:36 +00007603 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007604
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007605 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007606 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007607 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007608 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007609 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007610 R.getLookupKind(), S, &SS, CCC,
7611 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007612 // We reject any correction for which ND would be NULL.
7613 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007614
Richard Smithf9b15102013-08-17 00:46:16 +00007615 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007616 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007617 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7618 << NameInfo.getName() << LookupContext << 0
7619 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007620
7621 // If we corrected to an inheriting constructor, handle it as one.
7622 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7623 if (RD && RD->isInjectedClassName()) {
7624 // Fix up the information we'll use to build the using declaration.
7625 if (Corrected.WillReplaceSpecifier()) {
7626 NestedNameSpecifierLocBuilder Builder;
7627 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7628 QualifierLoc.getSourceRange());
7629 QualifierLoc = Builder.getWithLocInContext(Context);
7630 }
7631
7632 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7633 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007634 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007635
7636 // Build it and process it as an inheriting constructor.
7637 UsingDecl *UD = BuildValid();
7638 CheckInheritingConstructorUsingDecl(UD);
7639 return UD;
7640 }
7641
7642 // FIXME: Pick up all the declarations if we found an overloaded function.
7643 R.setLookupName(Corrected.getCorrection());
7644 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007645 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007646 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007647 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007648 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007649 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007650 }
7651
Richard Smith09d5b3a2014-05-01 00:35:04 +00007652 if (R.isAmbiguous())
7653 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007654
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007655 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007656 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007657 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007658 Diag(IdentLoc, diag::err_using_typename_non_type);
7659 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7660 Diag((*I)->getUnderlyingDecl()->getLocation(),
7661 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007662 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007663 }
7664 } else {
7665 // If we asked for a non-typename and we got a type, error out,
7666 // but only if this is an instantiation of an unresolved using
7667 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007668 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007669 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7670 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007671 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007672 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007673 }
7674
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007675 // C++0x N2914 [namespace.udecl]p6:
7676 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007677 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007678 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7679 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007680 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007681 }
Mike Stump11289f42009-09-09 15:08:12 +00007682
Richard Smith09d5b3a2014-05-01 00:35:04 +00007683 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007684 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007685 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007686 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7687 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007688 }
John McCall3f746822009-11-17 05:59:44 +00007689
7690 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007691}
7692
Sebastian Redl08905022011-02-05 19:23:19 +00007693/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007694bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007695 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007696
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007697 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007698 assert(SourceType &&
7699 "Using decl naming constructor doesn't have type in scope spec.");
7700 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7701
7702 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007703 bool AnyDependentBases = false;
7704 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7705 AnyDependentBases);
7706 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007707 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007708 diag::err_using_decl_constructor_not_in_direct_base)
7709 << UD->getNameInfo().getSourceRange()
7710 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007711 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007712 return true;
7713 }
7714
Richard Smith09d5b3a2014-05-01 00:35:04 +00007715 if (Base)
7716 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007717
7718 return false;
7719}
7720
John McCall84d87672009-12-10 09:41:52 +00007721/// Checks that the given using declaration is not an invalid
7722/// redeclaration. Note that this is checking only for the using decl
7723/// itself, not for any ill-formedness among the UsingShadowDecls.
7724bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007725 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007726 const CXXScopeSpec &SS,
7727 SourceLocation NameLoc,
7728 const LookupResult &Prev) {
7729 // C++03 [namespace.udecl]p8:
7730 // C++0x [namespace.udecl]p10:
7731 // A using-declaration is a declaration and can therefore be used
7732 // repeatedly where (and only where) multiple declarations are
7733 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007734 //
John McCall032092f2010-11-29 18:01:58 +00007735 // That's in non-member contexts.
7736 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007737 return false;
7738
Aaron Ballman4a979672014-01-03 13:56:08 +00007739 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007740
7741 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7742 NamedDecl *D = *I;
7743
7744 bool DTypename;
7745 NestedNameSpecifier *DQual;
7746 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007747 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007748 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007749 } else if (UnresolvedUsingValueDecl *UD
7750 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7751 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007752 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007753 } else if (UnresolvedUsingTypenameDecl *UD
7754 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7755 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007756 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007757 } else continue;
7758
7759 // using decls differ if one says 'typename' and the other doesn't.
7760 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007761 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007762
7763 // using decls differ if they name different scopes (but note that
7764 // template instantiation can cause this check to trigger when it
7765 // didn't before instantiation).
7766 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7767 Context.getCanonicalNestedNameSpecifier(DQual))
7768 continue;
7769
7770 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007771 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007772 return true;
7773 }
7774
7775 return false;
7776}
7777
John McCall3969e302009-12-08 07:46:18 +00007778
John McCallb96ec562009-12-04 22:46:56 +00007779/// Checks that the given nested-name qualifier used in a using decl
7780/// in the current context is appropriately related to the current
7781/// scope. If an error is found, diagnoses it and returns true.
7782bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7783 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007784 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007785 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007786 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007787
John McCall3969e302009-12-08 07:46:18 +00007788 if (!CurContext->isRecord()) {
7789 // C++03 [namespace.udecl]p3:
7790 // C++0x [namespace.udecl]p8:
7791 // A using-declaration for a class member shall be a member-declaration.
7792
7793 // If we weren't able to compute a valid scope, it must be a
7794 // dependent class scope.
7795 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007796 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7797 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00007798 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00007799
John McCall3969e302009-12-08 07:46:18 +00007800 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7801 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007802
7803 // If we have a complete, non-dependent source type, try to suggest a
7804 // way to get the same effect.
7805 if (!RD)
7806 return true;
7807
7808 // Find what this using-declaration was referring to.
7809 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7810 R.setHideTags(false);
7811 R.suppressDiagnostics();
7812 LookupQualifiedName(R, RD);
7813
7814 if (R.getAsSingle<TypeDecl>()) {
7815 if (getLangOpts().CPlusPlus11) {
7816 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7817 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7818 << 0 // alias declaration
7819 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7820 NameInfo.getName().getAsString() +
7821 " = ");
7822 } else {
7823 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7824 SourceLocation InsertLoc =
7825 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7826 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7827 << 1 // typedef declaration
7828 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7829 << FixItHint::CreateInsertion(
7830 InsertLoc, " " + NameInfo.getName().getAsString());
7831 }
7832 } else if (R.getAsSingle<VarDecl>()) {
7833 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7834 // repeating the type of the static data member here.
7835 FixItHint FixIt;
7836 if (getLangOpts().CPlusPlus11) {
7837 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7838 FixIt = FixItHint::CreateReplacement(
7839 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7840 }
7841
7842 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7843 << 2 // reference declaration
7844 << FixIt;
7845 }
John McCall3969e302009-12-08 07:46:18 +00007846 return true;
7847 }
7848
7849 // Otherwise, everything is known to be fine.
7850 return false;
7851 }
7852
7853 // The current scope is a record.
7854
7855 // If the named context is dependent, we can't decide much.
7856 if (!NamedContext) {
7857 // FIXME: in C++0x, we can diagnose if we can prove that the
7858 // nested-name-specifier does not refer to a base class, which is
7859 // still possible in some cases.
7860
7861 // Otherwise we have to conservatively report that things might be
7862 // okay.
7863 return false;
7864 }
7865
7866 if (!NamedContext->isRecord()) {
7867 // Ideally this would point at the last name in the specifier,
7868 // but we don't have that level of source info.
7869 Diag(SS.getRange().getBegin(),
7870 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007871 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007872 return true;
7873 }
7874
Douglas Gregor7c842292010-12-21 07:41:49 +00007875 if (!NamedContext->isDependentContext() &&
7876 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7877 return true;
7878
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007879 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007880 // C++0x [namespace.udecl]p3:
7881 // In a using-declaration used as a member-declaration, the
7882 // nested-name-specifier shall name a base class of the class
7883 // being defined.
7884
7885 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7886 cast<CXXRecordDecl>(NamedContext))) {
7887 if (CurContext == NamedContext) {
7888 Diag(NameLoc,
7889 diag::err_using_decl_nested_name_specifier_is_current_class)
7890 << SS.getRange();
7891 return true;
7892 }
7893
7894 Diag(SS.getRange().getBegin(),
7895 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007896 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007897 << cast<CXXRecordDecl>(CurContext)
7898 << SS.getRange();
7899 return true;
7900 }
7901
7902 return false;
7903 }
7904
7905 // C++03 [namespace.udecl]p4:
7906 // A using-declaration used as a member-declaration shall refer
7907 // to a member of a base class of the class being defined [etc.].
7908
7909 // Salient point: SS doesn't have to name a base class as long as
7910 // lookup only finds members from base classes. Therefore we can
7911 // diagnose here only if we can prove that that can't happen,
7912 // i.e. if the class hierarchies provably don't intersect.
7913
7914 // TODO: it would be nice if "definitely valid" results were cached
7915 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7916 // need to be repeated.
7917
7918 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007919 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007920
7921 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7922 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7923 Data->Bases.insert(Base);
7924 return true;
7925 }
7926
7927 bool hasDependentBases(const CXXRecordDecl *Class) {
7928 return !Class->forallBases(collect, this);
7929 }
7930
7931 /// Returns true if the base is dependent or is one of the
7932 /// accumulated base classes.
7933 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7934 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7935 return !Data->Bases.count(Base);
7936 }
7937
7938 bool mightShareBases(const CXXRecordDecl *Class) {
7939 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7940 }
7941 };
7942
7943 UserData Data;
7944
7945 // Returns false if we find a dependent base.
7946 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7947 return false;
7948
7949 // Returns false if the class has a dependent base or if it or one
7950 // of its bases is present in the base set of the current context.
7951 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7952 return false;
7953
7954 Diag(SS.getRange().getBegin(),
7955 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007956 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007957 << cast<CXXRecordDecl>(CurContext)
7958 << SS.getRange();
7959
7960 return true;
John McCallb96ec562009-12-04 22:46:56 +00007961}
7962
Richard Smithdda56e42011-04-15 14:24:37 +00007963Decl *Sema::ActOnAliasDeclaration(Scope *S,
7964 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007965 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007966 SourceLocation UsingLoc,
7967 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007968 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007969 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007970 // Skip up to the relevant declaration scope.
7971 while (S->getFlags() & Scope::TemplateParamScope)
7972 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007973 assert((S->getFlags() & Scope::DeclScope) &&
7974 "got alias-declaration outside of declaration scope");
7975
7976 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00007977 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00007978
7979 bool Invalid = false;
7980 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00007981 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00007982 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007983
7984 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00007985 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00007986
7987 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007988 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007989 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007990 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7991 TInfo->getTypeLoc().getBeginLoc());
7992 }
Richard Smithdda56e42011-04-15 14:24:37 +00007993
7994 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7995 LookupName(Previous, S);
7996
7997 // Warn about shadowing the name of a template parameter.
7998 if (Previous.isSingleResult() &&
7999 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008000 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008001 Previous.clear();
8002 }
8003
8004 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8005 "name in alias declaration must be an identifier");
8006 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8007 Name.StartLocation,
8008 Name.Identifier, TInfo);
8009
8010 NewTD->setAccess(AS);
8011
8012 if (Invalid)
8013 NewTD->setInvalidDecl();
8014
Richard Smith54ecd982013-02-20 19:22:51 +00008015 ProcessDeclAttributeList(S, NewTD, AttrList);
8016
Richard Smith3f1b5d02011-05-05 21:57:07 +00008017 CheckTypedefForVariablyModifiedType(S, NewTD);
8018 Invalid |= NewTD->isInvalidDecl();
8019
Richard Smithdda56e42011-04-15 14:24:37 +00008020 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008021
8022 NamedDecl *NewND;
8023 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008024 TypeAliasTemplateDecl *OldDecl = nullptr;
8025 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008026
8027 if (TemplateParamLists.size() != 1) {
8028 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008029 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8030 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008031 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008032 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008033
8034 // Only consider previous declarations in the same scope.
8035 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8036 /*ExplicitInstantiationOrSpecialization*/false);
8037 if (!Previous.empty()) {
8038 Redeclaration = true;
8039
8040 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8041 if (!OldDecl && !Invalid) {
8042 Diag(UsingLoc, diag::err_redefinition_different_kind)
8043 << Name.Identifier;
8044
8045 NamedDecl *OldD = Previous.getRepresentativeDecl();
8046 if (OldD->getLocation().isValid())
8047 Diag(OldD->getLocation(), diag::note_previous_definition);
8048
8049 Invalid = true;
8050 }
8051
8052 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8053 if (TemplateParameterListsAreEqual(TemplateParams,
8054 OldDecl->getTemplateParameters(),
8055 /*Complain=*/true,
8056 TPL_TemplateMatch))
8057 OldTemplateParams = OldDecl->getTemplateParameters();
8058 else
8059 Invalid = true;
8060
8061 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8062 if (!Invalid &&
8063 !Context.hasSameType(OldTD->getUnderlyingType(),
8064 NewTD->getUnderlyingType())) {
8065 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8066 // but we can't reasonably accept it.
8067 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8068 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8069 if (OldTD->getLocation().isValid())
8070 Diag(OldTD->getLocation(), diag::note_previous_definition);
8071 Invalid = true;
8072 }
8073 }
8074 }
8075
8076 // Merge any previous default template arguments into our parameters,
8077 // and check the parameter list.
8078 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8079 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008080 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008081
8082 TypeAliasTemplateDecl *NewDecl =
8083 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8084 Name.Identifier, TemplateParams,
8085 NewTD);
8086
8087 NewDecl->setAccess(AS);
8088
8089 if (Invalid)
8090 NewDecl->setInvalidDecl();
8091 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008092 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008093
8094 NewND = NewDecl;
8095 } else {
8096 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8097 NewND = NewTD;
8098 }
Richard Smithdda56e42011-04-15 14:24:37 +00008099
8100 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008101 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008102
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008103 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008104 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008105}
8106
John McCall48871652010-08-21 09:40:31 +00008107Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008108 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00008109 SourceLocation AliasLoc,
8110 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008111 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008112 SourceLocation IdentLoc,
8113 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008114
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008115 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008116 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8117 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008118
Anders Carlssondca83c42009-03-28 06:23:46 +00008119 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008120 NamedDecl *PrevDecl
8121 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8122 ForRedeclaration);
8123 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
Craig Topperc3ec1492014-05-26 06:22:03 +00008124 PrevDecl = nullptr;
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008125
8126 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008127 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00008128 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008129 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00008130 // FIXME: At some point, we'll want to create the (redundant)
8131 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00008132 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00008133 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00008134 return nullptr;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008135 }
Mike Stump11289f42009-09-09 15:08:12 +00008136
Anders Carlssondca83c42009-03-28 06:23:46 +00008137 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8138 diag::err_redefinition_different_kind;
8139 Diag(AliasLoc, DiagID) << Alias;
8140 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00008141 return nullptr;
Anders Carlssondca83c42009-03-28 06:23:46 +00008142 }
8143
John McCall27b18f82009-11-17 02:14:36 +00008144 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008145 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008146
John McCall9f3059a2009-10-09 21:13:30 +00008147 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008148 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008149 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008150 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008151 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008152 }
Mike Stump11289f42009-09-09 15:08:12 +00008153
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008154 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008155 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008156 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008157 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008158
John McCalld8d0d432010-02-16 06:53:13 +00008159 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008160 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008161}
8162
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008163Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008164Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8165 CXXMethodDecl *MD) {
8166 CXXRecordDecl *ClassDecl = MD->getParent();
8167
Douglas Gregor6d880b12010-07-01 22:31:05 +00008168 // C++ [except.spec]p14:
8169 // An implicitly declared special member function (Clause 12) shall have an
8170 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008171 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008172 if (ClassDecl->isInvalidDecl())
8173 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008174
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008175 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008176 for (const auto &B : ClassDecl->bases()) {
8177 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008178 continue;
8179
Aaron Ballman574705e2014-03-13 15:41:46 +00008180 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008181 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008182 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8183 // If this is a deleted function, add it anyway. This might be conformant
8184 // with the standard. This might not. I'm not sure. It might not matter.
8185 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008186 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008187 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008188 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008189
8190 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008191 for (const auto &B : ClassDecl->vbases()) {
8192 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008193 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008194 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8195 // If this is a deleted function, add it anyway. This might be conformant
8196 // with the standard. This might not. I'm not sure. It might not matter.
8197 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008198 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008199 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008200 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008201
8202 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008203 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008204 if (F->hasInClassInitializer()) {
8205 if (Expr *E = F->getInClassInitializer())
8206 ExceptSpec.CalledExpr(E);
8207 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008208 // DR1351:
8209 // If the brace-or-equal-initializer of a non-static data member
8210 // invokes a defaulted default constructor of its class or of an
8211 // enclosing class in a potentially evaluated subexpression, the
8212 // program is ill-formed.
8213 //
8214 // This resolution is unworkable: the exception specification of the
8215 // default constructor can be needed in an unevaluated context, in
8216 // particular, in the operand of a noexcept-expression, and we can be
8217 // unable to compute an exception specification for an enclosed class.
8218 //
8219 // We do not allow an in-class initializer to require the evaluation
8220 // of the exception specification for any in-class initializer whose
8221 // definition is not lexically complete.
8222 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008223 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008224 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008225 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8226 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8227 // If this is a deleted function, add it anyway. This might be conformant
8228 // with the standard. This might not. I'm not sure. It might not matter.
8229 // In particular, the problem is that this function never gets called. It
8230 // might just be ill-formed because this function attempts to refer to
8231 // a deleted function here.
8232 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008233 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008234 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008235 }
John McCalldb40c7f2010-12-14 08:05:40 +00008236
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008237 return ExceptSpec;
8238}
8239
Richard Smithc2bc61b2013-03-18 21:12:30 +00008240Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008241Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8242 CXXRecordDecl *ClassDecl = CD->getParent();
8243
8244 // C++ [except.spec]p14:
8245 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008246 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008247 if (ClassDecl->isInvalidDecl())
8248 return ExceptSpec;
8249
8250 // Inherited constructor.
8251 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8252 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8253 // FIXME: Copying or moving the parameters could add extra exceptions to the
8254 // set, as could the default arguments for the inherited constructor. This
8255 // will be addressed when we implement the resolution of core issue 1351.
8256 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8257
8258 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008259 for (const auto &B : ClassDecl->bases()) {
8260 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008261 continue;
8262
Aaron Ballman574705e2014-03-13 15:41:46 +00008263 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008264 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8265 if (BaseClassDecl == InheritedDecl)
8266 continue;
8267 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8268 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008269 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008270 }
8271 }
8272
8273 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008274 for (const auto &B : ClassDecl->vbases()) {
8275 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008276 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8277 if (BaseClassDecl == InheritedDecl)
8278 continue;
8279 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8280 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008281 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008282 }
8283 }
8284
8285 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008286 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008287 if (F->hasInClassInitializer()) {
8288 if (Expr *E = F->getInClassInitializer())
8289 ExceptSpec.CalledExpr(E);
8290 else if (!F->isInvalidDecl())
8291 Diag(CD->getLocation(),
8292 diag::err_in_class_initializer_references_def_ctor) << CD;
8293 } else if (const RecordType *RecordTy
8294 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8295 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8296 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8297 if (Constructor)
8298 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8299 }
8300 }
8301
Richard Smithc2bc61b2013-03-18 21:12:30 +00008302 return ExceptSpec;
8303}
8304
Richard Smith8bf22e52012-11-29 01:34:07 +00008305namespace {
8306/// RAII object to register a special member as being currently declared.
8307struct DeclaringSpecialMember {
8308 Sema &S;
8309 Sema::SpecialMemberDecl D;
8310 bool WasAlreadyBeingDeclared;
8311
8312 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8313 : S(S), D(RD, CSM) {
8314 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8315 if (WasAlreadyBeingDeclared)
8316 // This almost never happens, but if it does, ensure that our cache
8317 // doesn't contain a stale result.
8318 S.SpecialMemberCache.clear();
8319
8320 // FIXME: Register a note to be produced if we encounter an error while
8321 // declaring the special member.
8322 }
8323 ~DeclaringSpecialMember() {
8324 if (!WasAlreadyBeingDeclared)
8325 S.SpecialMembersBeingDeclared.erase(D);
8326 }
8327
8328 /// \brief Are we already trying to declare this special member?
8329 bool isAlreadyBeingDeclared() const {
8330 return WasAlreadyBeingDeclared;
8331 }
8332};
8333}
8334
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008335CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8336 CXXRecordDecl *ClassDecl) {
8337 // C++ [class.ctor]p5:
8338 // A default constructor for a class X is a constructor of class X
8339 // that can be called without an argument. If there is no
8340 // user-declared constructor for class X, a default constructor is
8341 // implicitly declared. An implicitly-declared default constructor
8342 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008343 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008344 "Should not build implicit default constructor!");
8345
Richard Smith8bf22e52012-11-29 01:34:07 +00008346 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8347 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008348 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008349
Richard Smithb5800092012-06-10 05:43:50 +00008350 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8351 CXXDefaultConstructor,
8352 false);
8353
Douglas Gregor6d880b12010-07-01 22:31:05 +00008354 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008355 CanQualType ClassType
8356 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008357 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008358 DeclarationName Name
8359 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008360 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008361 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008362 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8363 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8364 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008365 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008366 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008367 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008368
8369 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008370 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008371 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008372
Richard Smith6b02d462012-12-08 08:32:28 +00008373 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8374 // constructors is easy to compute.
8375 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8376
8377 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008378 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008379
Douglas Gregor9672f922010-07-03 00:47:00 +00008380 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008381 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008382
Douglas Gregor0be31a22010-07-02 17:43:08 +00008383 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008384 PushOnScopeChains(DefaultCon, S, false);
8385 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008386
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008387 return DefaultCon;
8388}
8389
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008390void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8391 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008392 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008393 !Constructor->doesThisDeclarationHaveABody() &&
8394 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008395 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008396
Anders Carlsson423f5d82010-04-23 16:04:08 +00008397 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008398 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008399
Eli Friedmaneaf34142012-10-18 20:14:08 +00008400 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008401 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008402 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008403 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008404 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008405 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008406 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008407 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008408 }
Douglas Gregor73193272010-09-20 16:48:21 +00008409
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008410 SourceLocation Loc = Constructor->getLocEnd().isValid()
8411 ? Constructor->getLocEnd()
8412 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008413 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008414
Eli Friedman276dd182013-09-05 00:02:25 +00008415 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008416 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008417
8418 if (ASTMutationListener *L = getASTMutationListener()) {
8419 L->CompletedImplicitDefinition(Constructor);
8420 }
Richard Trieuef64e942013-10-25 00:56:00 +00008421
8422 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008423}
8424
Richard Smith938f40b2011-06-11 17:19:42 +00008425void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008426 // Perform any delayed checks on exception specifications.
8427 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008428}
8429
Richard Smith185be182013-04-10 05:48:59 +00008430namespace {
8431/// Information on inheriting constructors to declare.
8432class InheritingConstructorInfo {
8433public:
8434 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8435 : SemaRef(SemaRef), Derived(Derived) {
8436 // Mark the constructors that we already have in the derived class.
8437 //
8438 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8439 // unless there is a user-declared constructor with the same signature in
8440 // the class where the using-declaration appears.
8441 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8442 }
8443
8444 void inheritAll(CXXRecordDecl *RD) {
8445 visitAll(RD, &InheritingConstructorInfo::inherit);
8446 }
8447
8448private:
8449 /// Information about an inheriting constructor.
8450 struct InheritingConstructor {
8451 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008452 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008453
8454 /// If \c true, a constructor with this signature is already declared
8455 /// in the derived class.
8456 bool DeclaredInDerived;
8457
8458 /// The constructor which is inherited.
8459 const CXXConstructorDecl *BaseCtor;
8460
8461 /// The derived constructor we declared.
8462 CXXConstructorDecl *DerivedCtor;
8463 };
8464
8465 /// Inheriting constructors with a given canonical type. There can be at
8466 /// most one such non-template constructor, and any number of templated
8467 /// constructors.
8468 struct InheritingConstructorsForType {
8469 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008470 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8471 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008472
8473 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8474 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8475 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8476 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8477 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8478 false, S.TPL_TemplateMatch))
8479 return Templates[I].second;
8480 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8481 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008482 }
Richard Smith185be182013-04-10 05:48:59 +00008483
8484 return NonTemplate;
8485 }
8486 };
8487
8488 /// Get or create the inheriting constructor record for a constructor.
8489 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8490 QualType CtorType) {
8491 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8492 .getEntry(SemaRef, Ctor);
8493 }
8494
8495 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8496
8497 /// Process all constructors for a class.
8498 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008499 for (const auto *Ctor : RD->ctors())
8500 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008501 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8502 I(RD->decls_begin()), E(RD->decls_end());
8503 I != E; ++I) {
8504 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8505 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8506 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008507 }
8508 }
Richard Smith185be182013-04-10 05:48:59 +00008509
8510 /// Note that a constructor (or constructor template) was declared in Derived.
8511 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8512 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8513 }
8514
8515 /// Inherit a single constructor.
8516 void inherit(const CXXConstructorDecl *Ctor) {
8517 const FunctionProtoType *CtorType =
8518 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008519 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008520 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8521
8522 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8523
8524 // Core issue (no number yet): the ellipsis is always discarded.
8525 if (EPI.Variadic) {
8526 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8527 SemaRef.Diag(Ctor->getLocation(),
8528 diag::note_using_decl_constructor_ellipsis);
8529 EPI.Variadic = false;
8530 }
8531
8532 // Declare a constructor for each number of parameters.
8533 //
8534 // C++11 [class.inhctor]p1:
8535 // The candidate set of inherited constructors from the class X named in
8536 // the using-declaration consists of [... modulo defects ...] for each
8537 // constructor or constructor template of X, the set of constructors or
8538 // constructor templates that results from omitting any ellipsis parameter
8539 // specification and successively omitting parameters with a default
8540 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008541 unsigned MinParams = minParamsToInherit(Ctor);
8542 unsigned Params = Ctor->getNumParams();
8543 if (Params >= MinParams) {
8544 do
8545 declareCtor(UsingLoc, Ctor,
8546 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008547 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008548 while (Params > MinParams &&
8549 Ctor->getParamDecl(--Params)->hasDefaultArg());
8550 }
Richard Smith185be182013-04-10 05:48:59 +00008551 }
8552
8553 /// Find the using-declaration which specified that we should inherit the
8554 /// constructors of \p Base.
8555 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8556 // No fancy lookup required; just look for the base constructor name
8557 // directly within the derived class.
8558 ASTContext &Context = SemaRef.Context;
8559 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8560 Context.getCanonicalType(Context.getRecordType(Base)));
8561 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8562 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8563 }
8564
8565 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8566 // C++11 [class.inhctor]p3:
8567 // [F]or each constructor template in the candidate set of inherited
8568 // constructors, a constructor template is implicitly declared
8569 if (Ctor->getDescribedFunctionTemplate())
8570 return 0;
8571
8572 // For each non-template constructor in the candidate set of inherited
8573 // constructors other than a constructor having no parameters or a
8574 // copy/move constructor having a single parameter, a constructor is
8575 // implicitly declared [...]
8576 if (Ctor->getNumParams() == 0)
8577 return 1;
8578 if (Ctor->isCopyOrMoveConstructor())
8579 return 2;
8580
8581 // Per discussion on core reflector, never inherit a constructor which
8582 // would become a default, copy, or move constructor of Derived either.
8583 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8584 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8585 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8586 }
8587
8588 /// Declare a single inheriting constructor, inheriting the specified
8589 /// constructor, with the given type.
8590 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8591 QualType DerivedType) {
8592 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8593
8594 // C++11 [class.inhctor]p3:
8595 // ... a constructor is implicitly declared with the same constructor
8596 // characteristics unless there is a user-declared constructor with
8597 // the same signature in the class where the using-declaration appears
8598 if (Entry.DeclaredInDerived)
8599 return;
8600
8601 // C++11 [class.inhctor]p7:
8602 // If two using-declarations declare inheriting constructors with the
8603 // same signature, the program is ill-formed
8604 if (Entry.DerivedCtor) {
8605 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8606 // Only diagnose this once per constructor.
8607 if (Entry.DerivedCtor->isInvalidDecl())
8608 return;
8609 Entry.DerivedCtor->setInvalidDecl();
8610
8611 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8612 SemaRef.Diag(BaseCtor->getLocation(),
8613 diag::note_using_decl_constructor_conflict_current_ctor);
8614 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8615 diag::note_using_decl_constructor_conflict_previous_ctor);
8616 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8617 diag::note_using_decl_constructor_conflict_previous_using);
8618 } else {
8619 // Core issue (no number): if the same inheriting constructor is
8620 // produced by multiple base class constructors from the same base
8621 // class, the inheriting constructor is defined as deleted.
8622 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8623 }
8624
8625 return;
8626 }
8627
8628 ASTContext &Context = SemaRef.Context;
8629 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8630 Context.getCanonicalType(Context.getRecordType(Derived)));
8631 DeclarationNameInfo NameInfo(Name, UsingLoc);
8632
Craig Topperc3ec1492014-05-26 06:22:03 +00008633 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008634 if (const FunctionTemplateDecl *FTD =
8635 BaseCtor->getDescribedFunctionTemplate()) {
8636 TemplateParams = FTD->getTemplateParameters();
8637 // We're reusing template parameters from a different DeclContext. This
8638 // is questionable at best, but works out because the template depth in
8639 // both places is guaranteed to be 0.
8640 // FIXME: Rebuild the template parameters in the new context, and
8641 // transform the function type to refer to them.
8642 }
8643
8644 // Build type source info pointing at the using-declaration. This is
8645 // required by template instantiation.
8646 TypeSourceInfo *TInfo =
8647 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8648 FunctionProtoTypeLoc ProtoLoc =
8649 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8650
8651 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8652 Context, Derived, UsingLoc, NameInfo, DerivedType,
8653 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8654 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8655
8656 // Build an unevaluated exception specification for this constructor.
8657 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8658 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8659 EPI.ExceptionSpecType = EST_Unevaluated;
8660 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008661 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008662 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008663
8664 // Build the parameter declarations.
8665 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008666 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008667 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008668 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008669 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008670 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8671 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00008672 PD->setScopeInfo(0, I);
8673 PD->setImplicit();
8674 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008675 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008676 }
8677
8678 // Set up the new constructor.
8679 DerivedCtor->setAccess(BaseCtor->getAccess());
8680 DerivedCtor->setParams(ParamDecls);
8681 DerivedCtor->setInheritedConstructor(BaseCtor);
8682 if (BaseCtor->isDeleted())
8683 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8684
8685 // If this is a constructor template, build the template declaration.
8686 if (TemplateParams) {
8687 FunctionTemplateDecl *DerivedTemplate =
8688 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8689 TemplateParams, DerivedCtor);
8690 DerivedTemplate->setAccess(BaseCtor->getAccess());
8691 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8692 Derived->addDecl(DerivedTemplate);
8693 } else {
8694 Derived->addDecl(DerivedCtor);
8695 }
8696
8697 Entry.BaseCtor = BaseCtor;
8698 Entry.DerivedCtor = DerivedCtor;
8699 }
8700
8701 Sema &SemaRef;
8702 CXXRecordDecl *Derived;
8703 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8704 MapType Map;
8705};
8706}
8707
8708void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8709 // Defer declaring the inheriting constructors until the class is
8710 // instantiated.
8711 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008712 return;
8713
Richard Smith185be182013-04-10 05:48:59 +00008714 // Find base classes from which we might inherit constructors.
8715 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008716 for (const auto &BaseIt : ClassDecl->bases())
8717 if (BaseIt.getInheritConstructors())
8718 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008719
Richard Smith185be182013-04-10 05:48:59 +00008720 // Go no further if we're not inheriting any constructors.
8721 if (InheritedBases.empty())
8722 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008723
Richard Smith185be182013-04-10 05:48:59 +00008724 // Declare the inherited constructors.
8725 InheritingConstructorInfo ICI(*this, ClassDecl);
8726 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8727 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008728}
8729
Richard Smithc2bc61b2013-03-18 21:12:30 +00008730void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8731 CXXConstructorDecl *Constructor) {
8732 CXXRecordDecl *ClassDecl = Constructor->getParent();
8733 assert(Constructor->getInheritedConstructor() &&
8734 !Constructor->doesThisDeclarationHaveABody() &&
8735 !Constructor->isDeleted());
8736
8737 SynthesizedFunctionScope Scope(*this, Constructor);
8738 DiagnosticErrorTrap Trap(Diags);
8739 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8740 Trap.hasErrorOccurred()) {
8741 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8742 << Context.getTagDeclType(ClassDecl);
8743 Constructor->setInvalidDecl();
8744 return;
8745 }
8746
8747 SourceLocation Loc = Constructor->getLocation();
8748 Constructor->setBody(new (Context) CompoundStmt(Loc));
8749
Eli Friedman276dd182013-09-05 00:02:25 +00008750 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008751 MarkVTableUsed(CurrentLocation, ClassDecl);
8752
8753 if (ASTMutationListener *L = getASTMutationListener()) {
8754 L->CompletedImplicitDefinition(Constructor);
8755 }
8756}
8757
8758
Alexis Huntf91729462011-05-12 22:46:25 +00008759Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008760Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8761 CXXRecordDecl *ClassDecl = MD->getParent();
8762
Douglas Gregorf1203042010-07-01 19:09:28 +00008763 // C++ [except.spec]p14:
8764 // An implicitly declared special member function (Clause 12) shall have
8765 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008766 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008767 if (ClassDecl->isInvalidDecl())
8768 return ExceptSpec;
8769
Douglas Gregorf1203042010-07-01 19:09:28 +00008770 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008771 for (const auto &B : ClassDecl->bases()) {
8772 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008773 continue;
8774
Aaron Ballman574705e2014-03-13 15:41:46 +00008775 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8776 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008777 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008778 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008779
Douglas Gregorf1203042010-07-01 19:09:28 +00008780 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008781 for (const auto &B : ClassDecl->vbases()) {
8782 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8783 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008784 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008785 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008786
Douglas Gregorf1203042010-07-01 19:09:28 +00008787 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008788 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008789 if (const RecordType *RecordTy
8790 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008791 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008792 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008793 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008794
Alexis Huntf91729462011-05-12 22:46:25 +00008795 return ExceptSpec;
8796}
8797
8798CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8799 // C++ [class.dtor]p2:
8800 // If a class has no user-declared destructor, a destructor is
8801 // declared implicitly. An implicitly-declared destructor is an
8802 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008803 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008804
Richard Smith8bf22e52012-11-29 01:34:07 +00008805 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8806 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008807 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008808
Douglas Gregor7454c562010-07-02 20:37:36 +00008809 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008810 CanQualType ClassType
8811 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008812 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008813 DeclarationName Name
8814 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008815 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008816 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008817 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00008818 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008819 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008820 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008821 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008822 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008823
8824 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008825 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008826 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008827
Richard Smith6b02d462012-12-08 08:32:28 +00008828 AddOverriddenMethods(ClassDecl, Destructor);
8829
8830 // We don't need to use SpecialMemberIsTrivial here; triviality for
8831 // destructors is easy to compute.
8832 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8833
8834 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008835 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008836
Douglas Gregor7454c562010-07-02 20:37:36 +00008837 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008838 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008839
Douglas Gregor7454c562010-07-02 20:37:36 +00008840 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008841 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008842 PushOnScopeChains(Destructor, S, false);
8843 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008844
Douglas Gregorf1203042010-07-01 19:09:28 +00008845 return Destructor;
8846}
8847
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008848void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008849 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008850 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008851 !Destructor->doesThisDeclarationHaveABody() &&
8852 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008853 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008854 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008855 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008856
Douglas Gregor54818f02010-05-12 16:39:35 +00008857 if (Destructor->isInvalidDecl())
8858 return;
8859
Eli Friedmaneaf34142012-10-18 20:14:08 +00008860 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008861
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008862 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008863 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8864 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008865
Douglas Gregor54818f02010-05-12 16:39:35 +00008866 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008867 Diag(CurrentLocation, diag::note_member_synthesized_at)
8868 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8869
8870 Destructor->setInvalidDecl();
8871 return;
8872 }
8873
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008874 SourceLocation Loc = Destructor->getLocEnd().isValid()
8875 ? Destructor->getLocEnd()
8876 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008877 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008878 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008879 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008880
8881 if (ASTMutationListener *L = getASTMutationListener()) {
8882 L->CompletedImplicitDefinition(Destructor);
8883 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008884}
8885
Richard Smith84973e52012-04-21 18:42:51 +00008886/// \brief Perform any semantic analysis which needs to be delayed until all
8887/// pending class member declarations have been parsed.
8888void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008889 // If the context is an invalid C++ class, just suppress these checks.
8890 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8891 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008892 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008893 DelayedDestructorExceptionSpecChecks.clear();
8894 return;
8895 }
8896 }
Richard Smith84973e52012-04-21 18:42:51 +00008897}
8898
Richard Smithd3b5c9082012-07-27 04:22:15 +00008899void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8900 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008901 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008902 "adjusting dtor exception specs was introduced in c++11");
8903
Sebastian Redl623ea822011-05-19 05:13:44 +00008904 // C++11 [class.dtor]p3:
8905 // A declaration of a destructor that does not have an exception-
8906 // specification is implicitly considered to have the same exception-
8907 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008908 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008909 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008910 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008911 return;
8912
Chandler Carruth9a797572011-09-20 04:55:26 +00008913 // Replace the destructor's type, building off the existing one. Fortunately,
8914 // the only thing of interest in the destructor type is its extended info.
8915 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008916 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8917 EPI.ExceptionSpecType = EST_Unevaluated;
8918 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008919 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008920
Sebastian Redl623ea822011-05-19 05:13:44 +00008921 // FIXME: If the destructor has a body that could throw, and the newly created
8922 // spec doesn't allow exceptions, we should emit a warning, because this
8923 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008924 // However, we don't have a body or an exception specification yet, so it
8925 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008926}
8927
Pavel Labath58934982013-08-30 08:52:28 +00008928namespace {
8929/// \brief An abstract base class for all helper classes used in building the
8930// copy/move operators. These classes serve as factory functions and help us
8931// avoid using the same Expr* in the AST twice.
8932class ExprBuilder {
8933 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8934 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8935
8936protected:
8937 static Expr *assertNotNull(Expr *E) {
8938 assert(E && "Expression construction must not fail.");
8939 return E;
8940 }
8941
8942public:
8943 ExprBuilder() {}
8944 virtual ~ExprBuilder() {}
8945
8946 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8947};
8948
8949class RefBuilder: public ExprBuilder {
8950 VarDecl *Var;
8951 QualType VarType;
8952
8953public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008954 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008955 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00008956 }
8957
8958 RefBuilder(VarDecl *Var, QualType VarType)
8959 : Var(Var), VarType(VarType) {}
8960};
8961
8962class ThisBuilder: public ExprBuilder {
8963public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008964 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008965 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00008966 }
8967};
8968
8969class CastBuilder: public ExprBuilder {
8970 const ExprBuilder &Builder;
8971 QualType Type;
8972 ExprValueKind Kind;
8973 const CXXCastPath &Path;
8974
8975public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008976 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008977 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8978 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008979 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00008980 }
8981
8982 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8983 const CXXCastPath &Path)
8984 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8985};
8986
8987class DerefBuilder: public ExprBuilder {
8988 const ExprBuilder &Builder;
8989
8990public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008991 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008992 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008993 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00008994 }
8995
8996 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8997};
8998
8999class MemberBuilder: public ExprBuilder {
9000 const ExprBuilder &Builder;
9001 QualType Type;
9002 CXXScopeSpec SS;
9003 bool IsArrow;
9004 LookupResult &MemberLookup;
9005
9006public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009007 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009008 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009009 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009010 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009011 }
9012
9013 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9014 LookupResult &MemberLookup)
9015 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9016 MemberLookup(MemberLookup) {}
9017};
9018
9019class MoveCastBuilder: public ExprBuilder {
9020 const ExprBuilder &Builder;
9021
9022public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009023 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009024 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9025 }
9026
9027 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9028};
9029
9030class LvalueConvBuilder: public ExprBuilder {
9031 const ExprBuilder &Builder;
9032
9033public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009034 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009035 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009036 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009037 }
9038
9039 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9040};
9041
9042class SubscriptBuilder: public ExprBuilder {
9043 const ExprBuilder &Base;
9044 const ExprBuilder &Index;
9045
9046public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009047 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009048 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009049 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009050 }
9051
9052 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9053 : Base(Base), Index(Index) {}
9054};
9055
9056} // end anonymous namespace
9057
Richard Smith41ae3282012-11-14 00:50:40 +00009058/// When generating a defaulted copy or move assignment operator, if a field
9059/// should be copied with __builtin_memcpy rather than via explicit assignments,
9060/// do so. This optimization only applies for arrays of scalars, and for arrays
9061/// of class type where the selected copy/move-assignment operator is trivial.
9062static StmtResult
9063buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009064 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009065 // Compute the size of the memory buffer to be copied.
9066 QualType SizeType = S.Context.getSizeType();
9067 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9068 S.Context.getTypeSizeInChars(T).getQuantity());
9069
9070 // Take the address of the field references for "from" and "to". We
9071 // directly construct UnaryOperators here because semantic analysis
9072 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009073 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009074 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9075 S.Context.getPointerType(From->getType()),
9076 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009077 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009078 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9079 S.Context.getPointerType(To->getType()),
9080 VK_RValue, OK_Ordinary, Loc);
9081
9082 const Type *E = T->getBaseElementTypeUnsafe();
9083 bool NeedsCollectableMemCpy =
9084 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9085
9086 // Create a reference to the __builtin_objc_memmove_collectable function
9087 StringRef MemCpyName = NeedsCollectableMemCpy ?
9088 "__builtin_objc_memmove_collectable" :
9089 "__builtin_memcpy";
9090 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9091 Sema::LookupOrdinaryName);
9092 S.LookupName(R, S.TUScope, true);
9093
9094 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9095 if (!MemCpy)
9096 // Something went horribly wrong earlier, and we will have complained
9097 // about it.
9098 return StmtError();
9099
9100 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009101 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009102 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9103
9104 Expr *CallArgs[] = {
9105 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9106 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009107 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009108 Loc, CallArgs, Loc);
9109
9110 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009111 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009112}
9113
Sebastian Redl22653ba2011-08-30 19:58:05 +00009114/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009115/// \c To.
9116///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009117/// This routine is used to copy/move the members of a class with an
9118/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009119/// copied are arrays, this routine builds for loops to copy them.
9120///
9121/// \param S The Sema object used for type-checking.
9122///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009123/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009124///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009125/// \param T The type of the expressions being copied/moved. Both expressions
9126/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009127///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009128/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009129///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009130/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009131///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009132/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009133/// Otherwise, it's a non-static member subobject.
9134///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009135/// \param Copying Whether we're copying or moving.
9136///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009137/// \param Depth Internal parameter recording the depth of the recursion.
9138///
Richard Smith41ae3282012-11-14 00:50:40 +00009139/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9140/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009141static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009142buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009143 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009144 bool CopyingBaseSubobject, bool Copying,
9145 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009146 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009147 // Each subobject is assigned in the manner appropriate to its type:
9148 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009149 // - if the subobject is of class type, as if by a call to operator= with
9150 // the subobject as the object expression and the corresponding
9151 // subobject of x as a single function argument (as if by explicit
9152 // qualification; that is, ignoring any possible virtual overriding
9153 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009154 //
9155 // C++03 [class.copy]p13:
9156 // - if the subobject is of class type, the copy assignment operator for
9157 // the class is used (as if by explicit qualification; that is,
9158 // ignoring any possible virtual overriding functions in more derived
9159 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009160 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9161 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009162
Douglas Gregorb139cd52010-05-01 20:49:11 +00009163 // Look for operator=.
9164 DeclarationName Name
9165 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9166 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9167 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009168
Richard Smith52c0b582012-11-13 00:54:12 +00009169 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9170 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009171 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009172 LookupResult::Filter F = OpLookup.makeFilter();
9173 while (F.hasNext()) {
9174 NamedDecl *D = F.next();
9175 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9176 if (Method->isCopyAssignmentOperator() ||
9177 (!Copying && Method->isMoveAssignmentOperator()))
9178 continue;
9179
9180 F.erase();
9181 }
9182 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009183 }
Richard Smith52c0b582012-11-13 00:54:12 +00009184
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009185 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009186 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009187 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009188 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009189 // ambiguities), we need to cast "this" to that subobject type; to
9190 // ensure that we don't go through the virtual call mechanism, we need
9191 // to qualify the operator= name with the base class (see below). However,
9192 // this means that if the base class has a protected copy assignment
9193 // operator, the protected member access check will fail. So, we
9194 // rewrite "protected" access to "public" access in this case, since we
9195 // know by construction that we're calling from a derived class.
9196 if (CopyingBaseSubobject) {
9197 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9198 L != LEnd; ++L) {
9199 if (L.getAccess() == AS_protected)
9200 L.setAccess(AS_public);
9201 }
9202 }
Richard Smith52c0b582012-11-13 00:54:12 +00009203
Douglas Gregorb139cd52010-05-01 20:49:11 +00009204 // Create the nested-name-specifier that will be used to qualify the
9205 // reference to operator=; this is required to suppress the virtual
9206 // call mechanism.
9207 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009208 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009209 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009210 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009211 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009212 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009213
Douglas Gregorb139cd52010-05-01 20:49:11 +00009214 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009215 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009216 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9217 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009218 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009219 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009220 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009221 /*SuppressQualifierCheck=*/true);
9222 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009223 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009224
Douglas Gregorb139cd52010-05-01 20:49:11 +00009225 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009226
Pavel Labath58934982013-08-30 08:52:28 +00009227 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009228 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009229 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009230 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009231 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009232 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009233
Richard Smith41ae3282012-11-14 00:50:40 +00009234 // If we built a call to a trivial 'operator=' while copying an array,
9235 // bail out. We'll replace the whole shebang with a memcpy.
9236 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9237 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009238 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009239
Richard Smith52c0b582012-11-13 00:54:12 +00009240 // Convert to an expression-statement, and clean up any produced
9241 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009242 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009243 }
John McCallab8c2732010-03-16 06:11:48 +00009244
Richard Smith52c0b582012-11-13 00:54:12 +00009245 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009246 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009247 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009248 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009249 ExprResult Assignment = S.CreateBuiltinBinOp(
9250 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009251 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009252 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009253 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009254 }
Richard Smith52c0b582012-11-13 00:54:12 +00009255
9256 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009257 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009258
Douglas Gregorb139cd52010-05-01 20:49:11 +00009259 // Construct a loop over the array bounds, e.g.,
9260 //
9261 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9262 //
9263 // that will copy each of the array elements.
9264 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009265
Douglas Gregorb139cd52010-05-01 20:49:11 +00009266 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009267 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009268 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009269 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009270 llvm::raw_svector_ostream OS(Str);
9271 OS << "__i" << Depth;
9272 IterationVarName = &S.Context.Idents.get(OS.str());
9273 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009274 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009275 IterationVarName, SizeType,
9276 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009277 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009278
Douglas Gregorb139cd52010-05-01 20:49:11 +00009279 // Initialize the iteration variable to zero.
9280 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009281 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009282
Pavel Labath58934982013-08-30 08:52:28 +00009283 // Creates a reference to the iteration variable.
9284 RefBuilder IterationVarRef(IterationVar, SizeType);
9285 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009286
Douglas Gregorb139cd52010-05-01 20:49:11 +00009287 // Create the DeclStmt that holds the iteration variable.
9288 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009289
Douglas Gregorb139cd52010-05-01 20:49:11 +00009290 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009291 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9292 MoveCastBuilder FromIndexMove(FromIndexCopy);
9293 const ExprBuilder *FromIndex;
9294 if (Copying)
9295 FromIndex = &FromIndexCopy;
9296 else
9297 FromIndex = &FromIndexMove;
9298
9299 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009300
9301 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009302 StmtResult Copy =
9303 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009304 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009305 Copying, Depth + 1);
9306 // Bail out if copying fails or if we determined that we should use memcpy.
9307 if (Copy.isInvalid() || !Copy.get())
9308 return Copy;
9309
9310 // Create the comparison against the array bound.
9311 llvm::APInt Upper
9312 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9313 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009314 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009315 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9316 BO_NE, S.Context.BoolTy,
9317 VK_RValue, OK_Ordinary, Loc, false);
9318
9319 // Create the pre-increment of the iteration variable.
9320 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009321 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9322 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009323
Douglas Gregorb139cd52010-05-01 20:49:11 +00009324 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009325 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009326 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009327 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009328 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009329}
9330
Richard Smith41ae3282012-11-14 00:50:40 +00009331static StmtResult
9332buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009333 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009334 bool CopyingBaseSubobject, bool Copying) {
9335 // Maybe we should use a memcpy?
9336 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9337 T.isTriviallyCopyableType(S.Context))
9338 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9339
9340 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9341 CopyingBaseSubobject,
9342 Copying, 0));
9343
9344 // If we ended up picking a trivial assignment operator for an array of a
9345 // non-trivially-copyable class type, just emit a memcpy.
9346 if (!Result.isInvalid() && !Result.get())
9347 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9348
9349 return Result;
9350}
9351
Richard Smithd3b5c9082012-07-27 04:22:15 +00009352Sema::ImplicitExceptionSpecification
9353Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9354 CXXRecordDecl *ClassDecl = MD->getParent();
9355
9356 ImplicitExceptionSpecification ExceptSpec(*this);
9357 if (ClassDecl->isInvalidDecl())
9358 return ExceptSpec;
9359
9360 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009361 assert(T->getNumParams() == 1 && "not a copy assignment op");
9362 unsigned ArgQuals =
9363 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009364
Douglas Gregor68e11362010-07-01 17:48:08 +00009365 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009366 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009367 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009368
9369 // It is unspecified whether or not an implicit copy assignment operator
9370 // attempts to deduplicate calls to assignment operators of virtual bases are
9371 // made. As such, this exception specification is effectively unspecified.
9372 // Based on a similar decision made for constness in C++0x, we're erring on
9373 // the side of assuming such calls to be made regardless of whether they
9374 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009375 for (const auto &Base : ClassDecl->bases()) {
9376 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009377 continue;
9378
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009379 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009380 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009381 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9382 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009383 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009384 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009385
Aaron Ballman445a9392014-03-13 16:15:17 +00009386 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009387 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009388 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009389 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9390 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009391 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009392 }
9393
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009394 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009395 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009396 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9397 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009398 LookupCopyingAssignment(FieldClassDecl,
9399 ArgQuals | FieldType.getCVRQualifiers(),
9400 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009401 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009402 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009403 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009404
Richard Smithd3b5c9082012-07-27 04:22:15 +00009405 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009406}
9407
9408CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9409 // Note: The following rules are largely analoguous to the copy
9410 // constructor rules. Note that virtual bases are not taken into account
9411 // for determining the argument type of the operator. Note also that
9412 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009413 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009414
Richard Smith8bf22e52012-11-29 01:34:07 +00009415 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9416 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009417 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009418
Alexis Hunt119f3652011-05-14 05:23:20 +00009419 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9420 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009421 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9422 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009423 ArgType = ArgType.withConst();
9424 ArgType = Context.getLValueReferenceType(ArgType);
9425
Richard Smith99005e62013-05-07 03:19:20 +00009426 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9427 CXXCopyAssignment,
9428 Const);
9429
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009430 // An implicitly-declared copy assignment operator is an inline public
9431 // member of its class.
9432 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009433 SourceLocation ClassLoc = ClassDecl->getLocation();
9434 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009435 CXXMethodDecl *CopyAssignment =
9436 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009437 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9438 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009439 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009440 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009441 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009442
9443 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009444 FunctionProtoType::ExtProtoInfo EPI =
9445 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009446 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009447
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009448 // Add the parameter to the operator.
9449 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009450 ClassLoc, ClassLoc,
9451 /*Id=*/nullptr, ArgType,
9452 /*TInfo=*/nullptr, SC_None,
9453 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009454 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009455
Richard Smith6b02d462012-12-08 08:32:28 +00009456 AddOverriddenMethods(ClassDecl, CopyAssignment);
9457
9458 CopyAssignment->setTrivial(
9459 ClassDecl->needsOverloadResolutionForCopyAssignment()
9460 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9461 : ClassDecl->hasTrivialCopyAssignment());
9462
Richard Smith852265f2012-03-30 20:53:28 +00009463 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009464 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009465
Richard Smith6b02d462012-12-08 08:32:28 +00009466 // Note that we have added this copy-assignment operator.
9467 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9468
9469 if (Scope *S = getScopeForContext(ClassDecl))
9470 PushOnScopeChains(CopyAssignment, S, false);
9471 ClassDecl->addDecl(CopyAssignment);
9472
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009473 return CopyAssignment;
9474}
9475
Richard Smithd577fbb2013-06-13 03:23:42 +00009476/// Diagnose an implicit copy operation for a class which is odr-used, but
9477/// which is deprecated because the class has a user-declared copy constructor,
9478/// copy assignment operator, or destructor.
9479static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9480 SourceLocation UseLoc) {
9481 assert(CopyOp->isImplicit());
9482
9483 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009484 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009485
9486 // In Microsoft mode, assignment operations don't affect constructors and
9487 // vice versa.
9488 if (RD->hasUserDeclaredDestructor()) {
9489 UserDeclaredOperation = RD->getDestructor();
9490 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9491 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009492 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009493 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009494 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009495 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009496 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009497 break;
9498 }
9499 }
9500 assert(UserDeclaredOperation);
9501 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9502 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009503 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009504 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009505 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009506 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009507 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009508 break;
9509 }
9510 }
9511 assert(UserDeclaredOperation);
9512 }
9513
9514 if (UserDeclaredOperation) {
9515 S.Diag(UserDeclaredOperation->getLocation(),
9516 diag::warn_deprecated_copy_operation)
9517 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9518 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9519 S.Diag(UseLoc, diag::note_member_synthesized_at)
9520 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9521 : Sema::CXXCopyAssignment)
9522 << RD;
9523 }
9524}
9525
Douglas Gregorb139cd52010-05-01 20:49:11 +00009526void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9527 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009528 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009529 CopyAssignOperator->isOverloadedOperator() &&
9530 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009531 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9532 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009533 "DefineImplicitCopyAssignment called for wrong function");
9534
9535 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9536
9537 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9538 CopyAssignOperator->setInvalidDecl();
9539 return;
9540 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009541
9542 // C++11 [class.copy]p18:
9543 // The [definition of an implicitly declared copy assignment operator] is
9544 // deprecated if the class has a user-declared copy constructor or a
9545 // user-declared destructor.
9546 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9547 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9548
Eli Friedman276dd182013-09-05 00:02:25 +00009549 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009550
Eli Friedmaneaf34142012-10-18 20:14:08 +00009551 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009552 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009553
9554 // C++0x [class.copy]p30:
9555 // The implicitly-defined or explicitly-defaulted copy assignment operator
9556 // for a non-union class X performs memberwise copy assignment of its
9557 // subobjects. The direct base classes of X are assigned first, in the
9558 // order of their declaration in the base-specifier-list, and then the
9559 // immediate non-static data members of X are assigned, in the order in
9560 // which they were declared in the class definition.
9561
9562 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009563 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009564
9565 // The parameter for the "other" object, which we are copying from.
9566 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9567 Qualifiers OtherQuals = Other->getType().getQualifiers();
9568 QualType OtherRefType = Other->getType();
9569 if (const LValueReferenceType *OtherRef
9570 = OtherRefType->getAs<LValueReferenceType>()) {
9571 OtherRefType = OtherRef->getPointeeType();
9572 OtherQuals = OtherRefType.getQualifiers();
9573 }
9574
9575 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009576 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9577 ? CopyAssignOperator->getLocEnd()
9578 : CopyAssignOperator->getLocation();
9579
Pavel Labath58934982013-08-30 08:52:28 +00009580 // Builds a DeclRefExpr for the "other" object.
9581 RefBuilder OtherRef(Other, OtherRefType);
9582
9583 // Builds the "this" pointer.
9584 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009585
9586 // Assign base classes.
9587 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009588 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009589 // Form the assignment:
9590 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009591 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009592 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009593 Invalid = true;
9594 continue;
9595 }
9596
John McCallcf142162010-08-07 06:22:56 +00009597 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009598 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009599
Douglas Gregorb139cd52010-05-01 20:49:11 +00009600 // Construct the "from" expression, which is an implicit cast to the
9601 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009602 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9603 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009604
9605 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009606 DerefBuilder DerefThis(This);
9607 CastBuilder To(DerefThis,
9608 Context.getCVRQualifiedType(
9609 BaseType, CopyAssignOperator->getTypeQualifiers()),
9610 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009611
9612 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009613 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009614 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009615 /*CopyingBaseSubobject=*/true,
9616 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009617 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009618 Diag(CurrentLocation, diag::note_member_synthesized_at)
9619 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9620 CopyAssignOperator->setInvalidDecl();
9621 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009622 }
9623
9624 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009625 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009626 }
9627
Douglas Gregorb139cd52010-05-01 20:49:11 +00009628 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009629 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009630 if (Field->isUnnamedBitfield())
9631 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009632
9633 if (Field->isInvalidDecl()) {
9634 Invalid = true;
9635 continue;
9636 }
9637
Douglas Gregorb139cd52010-05-01 20:49:11 +00009638 // Check for members of reference type; we can't copy those.
9639 if (Field->getType()->isReferenceType()) {
9640 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9641 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9642 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009643 Diag(CurrentLocation, diag::note_member_synthesized_at)
9644 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009645 Invalid = true;
9646 continue;
9647 }
9648
9649 // Check for members of const-qualified, non-class type.
9650 QualType BaseType = Context.getBaseElementType(Field->getType());
9651 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9652 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9653 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9654 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009655 Diag(CurrentLocation, diag::note_member_synthesized_at)
9656 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009657 Invalid = true;
9658 continue;
9659 }
John McCall1b1a1db2011-06-17 00:18:42 +00009660
9661 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009662 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9663 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009664
9665 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009666 if (FieldType->isIncompleteArrayType()) {
9667 assert(ClassDecl->hasFlexibleArrayMember() &&
9668 "Incomplete array type is not valid");
9669 continue;
9670 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009671
9672 // Build references to the field in the object we're copying from and to.
9673 CXXScopeSpec SS; // Intentionally empty
9674 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9675 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009676 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009677 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009678
9679 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9680
9681 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009682
Douglas Gregorb139cd52010-05-01 20:49:11 +00009683 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009684 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009685 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009686 /*CopyingBaseSubobject=*/false,
9687 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009688 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009689 Diag(CurrentLocation, diag::note_member_synthesized_at)
9690 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9691 CopyAssignOperator->setInvalidDecl();
9692 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009693 }
9694
9695 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009696 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009697 }
9698
9699 if (!Invalid) {
9700 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009701 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009702
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009703 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009704 if (Return.isInvalid())
9705 Invalid = true;
9706 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009707 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009708
9709 if (Trap.hasErrorOccurred()) {
9710 Diag(CurrentLocation, diag::note_member_synthesized_at)
9711 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9712 Invalid = true;
9713 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009714 }
9715 }
9716
9717 if (Invalid) {
9718 CopyAssignOperator->setInvalidDecl();
9719 return;
9720 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009721
9722 StmtResult Body;
9723 {
9724 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009725 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009726 /*isStmtExpr=*/false);
9727 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9728 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009729 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009730
9731 if (ASTMutationListener *L = getASTMutationListener()) {
9732 L->CompletedImplicitDefinition(CopyAssignOperator);
9733 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009734}
9735
Sebastian Redl22653ba2011-08-30 19:58:05 +00009736Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009737Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9738 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009739
Richard Smithd3b5c9082012-07-27 04:22:15 +00009740 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009741 if (ClassDecl->isInvalidDecl())
9742 return ExceptSpec;
9743
9744 // C++0x [except.spec]p14:
9745 // An implicitly declared special member function (Clause 12) shall have an
9746 // exception-specification. [...]
9747
9748 // It is unspecified whether or not an implicit move assignment operator
9749 // attempts to deduplicate calls to assignment operators of virtual bases are
9750 // made. As such, this exception specification is effectively unspecified.
9751 // Based on a similar decision made for constness in C++0x, we're erring on
9752 // the side of assuming such calls to be made regardless of whether they
9753 // actually happen.
9754 // Note that a move constructor is not implicitly declared when there are
9755 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009756 for (const auto &Base : ClassDecl->bases()) {
9757 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009758 continue;
9759
9760 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009761 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009762 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009763 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009764 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009765 }
9766
Aaron Ballman445a9392014-03-13 16:15:17 +00009767 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009768 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009769 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009770 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009771 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009772 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009773 }
9774
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009775 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009776 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009777 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009778 if (CXXMethodDecl *MoveAssign =
9779 LookupMovingAssignment(FieldClassDecl,
9780 FieldType.getCVRQualifiers(),
9781 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009782 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009783 }
9784 }
9785
9786 return ExceptSpec;
9787}
9788
9789CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009790 assert(ClassDecl->needsImplicitMoveAssignment());
9791
Richard Smith8bf22e52012-11-29 01:34:07 +00009792 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9793 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009794 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009795
Sebastian Redl22653ba2011-08-30 19:58:05 +00009796 // Note: The following rules are largely analoguous to the move
9797 // constructor rules.
9798
Sebastian Redl22653ba2011-08-30 19:58:05 +00009799 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9800 QualType RetType = Context.getLValueReferenceType(ArgType);
9801 ArgType = Context.getRValueReferenceType(ArgType);
9802
Richard Smith99005e62013-05-07 03:19:20 +00009803 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9804 CXXMoveAssignment,
9805 false);
9806
Sebastian Redl22653ba2011-08-30 19:58:05 +00009807 // An implicitly-declared move assignment operator is an inline public
9808 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009809 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9810 SourceLocation ClassLoc = ClassDecl->getLocation();
9811 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009812 CXXMethodDecl *MoveAssignment =
9813 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009814 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +00009815 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009816 MoveAssignment->setAccess(AS_public);
9817 MoveAssignment->setDefaulted();
9818 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009819
Richard Smithd3b5c9082012-07-27 04:22:15 +00009820 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009821 FunctionProtoType::ExtProtoInfo EPI =
9822 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009823 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009824
Sebastian Redl22653ba2011-08-30 19:58:05 +00009825 // Add the parameter to the operator.
9826 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009827 ClassLoc, ClassLoc,
9828 /*Id=*/nullptr, ArgType,
9829 /*TInfo=*/nullptr, SC_None,
9830 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009831 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009832
Richard Smith6b02d462012-12-08 08:32:28 +00009833 AddOverriddenMethods(ClassDecl, MoveAssignment);
9834
9835 MoveAssignment->setTrivial(
9836 ClassDecl->needsOverloadResolutionForMoveAssignment()
9837 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9838 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009839
Richard Smithd951a1d2012-02-18 02:02:13 +00009840 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009841 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9842 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009843 }
9844
Richard Smith6b02d462012-12-08 08:32:28 +00009845 // Note that we have added this copy-assignment operator.
9846 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9847
Sebastian Redl22653ba2011-08-30 19:58:05 +00009848 if (Scope *S = getScopeForContext(ClassDecl))
9849 PushOnScopeChains(MoveAssignment, S, false);
9850 ClassDecl->addDecl(MoveAssignment);
9851
Sebastian Redl22653ba2011-08-30 19:58:05 +00009852 return MoveAssignment;
9853}
9854
Richard Smithb2504bd2013-11-04 04:26:14 +00009855/// Check if we're implicitly defining a move assignment operator for a class
9856/// with virtual bases. Such a move assignment might move-assign the virtual
9857/// base multiple times.
9858static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9859 SourceLocation CurrentLocation) {
9860 assert(!Class->isDependentContext() && "should not define dependent move");
9861
9862 // Only a virtual base could get implicitly move-assigned multiple times.
9863 // Only a non-trivial move assignment can observe this. We only want to
9864 // diagnose if we implicitly define an assignment operator that assigns
9865 // two base classes, both of which move-assign the same virtual base.
9866 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9867 Class->getNumBases() < 2)
9868 return;
9869
9870 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9871 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9872 VBaseMap VBases;
9873
Aaron Ballman574705e2014-03-13 15:41:46 +00009874 for (auto &BI : Class->bases()) {
9875 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009876 while (!Worklist.empty()) {
9877 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9878 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9879
9880 // If the base has no non-trivial move assignment operators,
9881 // we don't care about moves from it.
9882 if (!Base->hasNonTrivialMoveAssignment())
9883 continue;
9884
9885 // If there's nothing virtual here, skip it.
9886 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9887 continue;
9888
9889 // If we're not actually going to call a move assignment for this base,
9890 // or the selected move assignment is trivial, skip it.
9891 Sema::SpecialMemberOverloadResult *SMOR =
9892 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9893 /*ConstArg*/false, /*VolatileArg*/false,
9894 /*RValueThis*/true, /*ConstThis*/false,
9895 /*VolatileThis*/false);
9896 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9897 !SMOR->getMethod()->isMoveAssignmentOperator())
9898 continue;
9899
9900 if (BaseSpec->isVirtual()) {
9901 // We're going to move-assign this virtual base, and its move
9902 // assignment operator is not trivial. If this can happen for
9903 // multiple distinct direct bases of Class, diagnose it. (If it
9904 // only happens in one base, we'll diagnose it when synthesizing
9905 // that base class's move assignment operator.)
9906 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009907 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009908 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009909 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009910 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9911 << Class << Base;
9912 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9913 << (Base->getCanonicalDecl() ==
9914 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9915 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009916 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009917 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009918 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9919 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009920
9921 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +00009922 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +00009923 }
9924 } else {
9925 // Only walk over bases that have defaulted move assignment operators.
9926 // We assume that any user-provided move assignment operator handles
9927 // the multiple-moves-of-vbase case itself somehow.
9928 if (!SMOR->getMethod()->isDefaulted())
9929 continue;
9930
9931 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009932 for (auto &BI : Base->bases())
9933 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009934 }
9935 }
9936 }
9937}
9938
Sebastian Redl22653ba2011-08-30 19:58:05 +00009939void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9940 CXXMethodDecl *MoveAssignOperator) {
9941 assert((MoveAssignOperator->isDefaulted() &&
9942 MoveAssignOperator->isOverloadedOperator() &&
9943 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009944 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9945 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009946 "DefineImplicitMoveAssignment called for wrong function");
9947
9948 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9949
9950 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9951 MoveAssignOperator->setInvalidDecl();
9952 return;
9953 }
9954
Eli Friedman276dd182013-09-05 00:02:25 +00009955 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009956
Eli Friedmaneaf34142012-10-18 20:14:08 +00009957 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009958 DiagnosticErrorTrap Trap(Diags);
9959
9960 // C++0x [class.copy]p28:
9961 // The implicitly-defined or move assignment operator for a non-union class
9962 // X performs memberwise move assignment of its subobjects. The direct base
9963 // classes of X are assigned first, in the order of their declaration in the
9964 // base-specifier-list, and then the immediate non-static data members of X
9965 // are assigned, in the order in which they were declared in the class
9966 // definition.
9967
Richard Smithb2504bd2013-11-04 04:26:14 +00009968 // Issue a warning if our implicit move assignment operator will move
9969 // from a virtual base more than once.
9970 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009971
Sebastian Redl22653ba2011-08-30 19:58:05 +00009972 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009973 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009974
9975 // The parameter for the "other" object, which we are move from.
9976 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9977 QualType OtherRefType = Other->getType()->
9978 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009979 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009980 "Bad argument type of defaulted move assignment");
9981
9982 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009983 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
9984 ? MoveAssignOperator->getLocEnd()
9985 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009986
Pavel Labath58934982013-08-30 08:52:28 +00009987 // Builds a reference to the "other" object.
9988 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009989 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009990 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009991
Pavel Labath58934982013-08-30 08:52:28 +00009992 // Builds the "this" pointer.
9993 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009994
Sebastian Redl22653ba2011-08-30 19:58:05 +00009995 // Assign base classes.
9996 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009997 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009998 // C++11 [class.copy]p28:
9999 // It is unspecified whether subobjects representing virtual base classes
10000 // are assigned more than once by the implicitly-defined copy assignment
10001 // operator.
10002 // FIXME: Do not assign to a vbase that will be assigned by some other base
10003 // class. For a move-assignment, this can result in the vbase being moved
10004 // multiple times.
10005
Sebastian Redl22653ba2011-08-30 19:58:05 +000010006 // Form the assignment:
10007 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010008 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010009 if (!BaseType->isRecordType()) {
10010 Invalid = true;
10011 continue;
10012 }
10013
10014 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010015 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010016
10017 // Construct the "from" expression, which is an implicit cast to the
10018 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010019 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010020
10021 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010022 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010023
10024 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010025 CastBuilder To(DerefThis,
10026 Context.getCVRQualifiedType(
10027 BaseType, MoveAssignOperator->getTypeQualifiers()),
10028 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010029
10030 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010031 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010032 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010033 /*CopyingBaseSubobject=*/true,
10034 /*Copying=*/false);
10035 if (Move.isInvalid()) {
10036 Diag(CurrentLocation, diag::note_member_synthesized_at)
10037 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10038 MoveAssignOperator->setInvalidDecl();
10039 return;
10040 }
10041
10042 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010043 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010044 }
10045
Sebastian Redl22653ba2011-08-30 19:58:05 +000010046 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010047 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010048 if (Field->isUnnamedBitfield())
10049 continue;
10050
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010051 if (Field->isInvalidDecl()) {
10052 Invalid = true;
10053 continue;
10054 }
10055
Sebastian Redl22653ba2011-08-30 19:58:05 +000010056 // Check for members of reference type; we can't move those.
10057 if (Field->getType()->isReferenceType()) {
10058 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10059 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10060 Diag(Field->getLocation(), diag::note_declared_at);
10061 Diag(CurrentLocation, diag::note_member_synthesized_at)
10062 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10063 Invalid = true;
10064 continue;
10065 }
10066
10067 // Check for members of const-qualified, non-class type.
10068 QualType BaseType = Context.getBaseElementType(Field->getType());
10069 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10070 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10071 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10072 Diag(Field->getLocation(), diag::note_declared_at);
10073 Diag(CurrentLocation, diag::note_member_synthesized_at)
10074 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10075 Invalid = true;
10076 continue;
10077 }
10078
10079 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010080 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10081 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010082
10083 QualType FieldType = Field->getType().getNonReferenceType();
10084 if (FieldType->isIncompleteArrayType()) {
10085 assert(ClassDecl->hasFlexibleArrayMember() &&
10086 "Incomplete array type is not valid");
10087 continue;
10088 }
10089
10090 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010091 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10092 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010093 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010094 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010095 MemberBuilder From(MoveOther, OtherRefType,
10096 /*IsArrow=*/false, MemberLookup);
10097 MemberBuilder To(This, getCurrentThisType(),
10098 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010099
Pavel Labath58934982013-08-30 08:52:28 +000010100 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010101 "Member reference with rvalue base must be rvalue except for reference "
10102 "members, which aren't allowed for move assignment.");
10103
Sebastian Redl22653ba2011-08-30 19:58:05 +000010104 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010105 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010106 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010107 /*CopyingBaseSubobject=*/false,
10108 /*Copying=*/false);
10109 if (Move.isInvalid()) {
10110 Diag(CurrentLocation, diag::note_member_synthesized_at)
10111 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10112 MoveAssignOperator->setInvalidDecl();
10113 return;
10114 }
Richard Smith11d19592012-11-12 23:33:00 +000010115
Sebastian Redl22653ba2011-08-30 19:58:05 +000010116 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010117 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010118 }
10119
10120 if (!Invalid) {
10121 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010122 ExprResult ThisObj =
10123 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10124
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010125 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010126 if (Return.isInvalid())
10127 Invalid = true;
10128 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010129 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010130
10131 if (Trap.hasErrorOccurred()) {
10132 Diag(CurrentLocation, diag::note_member_synthesized_at)
10133 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10134 Invalid = true;
10135 }
10136 }
10137 }
10138
10139 if (Invalid) {
10140 MoveAssignOperator->setInvalidDecl();
10141 return;
10142 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010143
10144 StmtResult Body;
10145 {
10146 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010147 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010148 /*isStmtExpr=*/false);
10149 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10150 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010151 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010152
10153 if (ASTMutationListener *L = getASTMutationListener()) {
10154 L->CompletedImplicitDefinition(MoveAssignOperator);
10155 }
10156}
10157
Richard Smithd3b5c9082012-07-27 04:22:15 +000010158Sema::ImplicitExceptionSpecification
10159Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10160 CXXRecordDecl *ClassDecl = MD->getParent();
10161
10162 ImplicitExceptionSpecification ExceptSpec(*this);
10163 if (ClassDecl->isInvalidDecl())
10164 return ExceptSpec;
10165
10166 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010167 assert(T->getNumParams() >= 1 && "not a copy ctor");
10168 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010169
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010170 // C++ [except.spec]p14:
10171 // An implicitly declared special member function (Clause 12) shall have an
10172 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010173 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010174 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010175 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010176 continue;
10177
Douglas Gregora6d69502010-07-02 23:41:54 +000010178 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010179 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010180 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010181 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010182 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010183 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010184 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010185 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010186 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010187 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010188 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010189 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010190 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010191 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010192 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010193 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10194 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010195 LookupCopyingConstructor(FieldClassDecl,
10196 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010197 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010198 }
10199 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010200
Richard Smithd3b5c9082012-07-27 04:22:15 +000010201 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010202}
10203
10204CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10205 CXXRecordDecl *ClassDecl) {
10206 // C++ [class.copy]p4:
10207 // If the class definition does not explicitly declare a copy
10208 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010209 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010210
Richard Smith8bf22e52012-11-29 01:34:07 +000010211 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10212 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010213 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010214
Alexis Hunt913820d2011-05-13 06:10:58 +000010215 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10216 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010217 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010218 if (Const)
10219 ArgType = ArgType.withConst();
10220 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010221
Richard Smithb5800092012-06-10 05:43:50 +000010222 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10223 CXXCopyConstructor,
10224 Const);
10225
Douglas Gregor54be3392010-07-01 17:57:27 +000010226 DeclarationName Name
10227 = Context.DeclarationNames.getCXXConstructorName(
10228 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010229 SourceLocation ClassLoc = ClassDecl->getLocation();
10230 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010231
10232 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010233 // member of its class.
10234 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010235 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010236 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010237 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010238 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010239 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010240
Richard Smithd3b5c9082012-07-27 04:22:15 +000010241 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010242 FunctionProtoType::ExtProtoInfo EPI =
10243 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010244 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010245 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010246
Douglas Gregor54be3392010-07-01 17:57:27 +000010247 // Add the parameter to the constructor.
10248 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010249 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010250 /*IdentifierInfo=*/nullptr,
10251 ArgType, /*TInfo=*/nullptr,
10252 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010253 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010254
Richard Smith6b02d462012-12-08 08:32:28 +000010255 CopyConstructor->setTrivial(
10256 ClassDecl->needsOverloadResolutionForCopyConstructor()
10257 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10258 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010259
Richard Smith852265f2012-03-30 20:53:28 +000010260 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010261 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010262
Richard Smith6b02d462012-12-08 08:32:28 +000010263 // Note that we have declared this constructor.
10264 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10265
10266 if (Scope *S = getScopeForContext(ClassDecl))
10267 PushOnScopeChains(CopyConstructor, S, false);
10268 ClassDecl->addDecl(CopyConstructor);
10269
Douglas Gregor54be3392010-07-01 17:57:27 +000010270 return CopyConstructor;
10271}
10272
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010273void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010274 CXXConstructorDecl *CopyConstructor) {
10275 assert((CopyConstructor->isDefaulted() &&
10276 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010277 !CopyConstructor->doesThisDeclarationHaveABody() &&
10278 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010279 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010280
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010281 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010282 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010283
Richard Smithd577fbb2013-06-13 03:23:42 +000010284 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010285 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010286 // deprecated if the class has a user-declared copy assignment operator
10287 // or a user-declared destructor.
10288 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10289 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10290
Eli Friedmaneaf34142012-10-18 20:14:08 +000010291 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010292 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010293
David Blaikie3fc2f912013-01-17 05:26:25 +000010294 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010295 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010296 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010297 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010298 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010299 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010300 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10301 ? CopyConstructor->getLocEnd()
10302 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010303 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010304 CopyConstructor->setBody(
10305 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010306 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010307
Eli Friedman276dd182013-09-05 00:02:25 +000010308 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010309 if (ASTMutationListener *L = getASTMutationListener()) {
10310 L->CompletedImplicitDefinition(CopyConstructor);
10311 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010312}
10313
Sebastian Redl22653ba2011-08-30 19:58:05 +000010314Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010315Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10316 CXXRecordDecl *ClassDecl = MD->getParent();
10317
Sebastian Redl22653ba2011-08-30 19:58:05 +000010318 // C++ [except.spec]p14:
10319 // An implicitly declared special member function (Clause 12) shall have an
10320 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010321 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010322 if (ClassDecl->isInvalidDecl())
10323 return ExceptSpec;
10324
10325 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010326 for (const auto &B : ClassDecl->bases()) {
10327 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010328 continue;
10329
Aaron Ballman574705e2014-03-13 15:41:46 +000010330 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010331 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010332 CXXConstructorDecl *Constructor =
10333 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010334 // If this is a deleted function, add it anyway. This might be conformant
10335 // with the standard. This might not. I'm not sure. It might not matter.
10336 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010337 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010338 }
10339 }
10340
10341 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010342 for (const auto &B : ClassDecl->vbases()) {
10343 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010345 CXXConstructorDecl *Constructor =
10346 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010347 // If this is a deleted function, add it anyway. This might be conformant
10348 // with the standard. This might not. I'm not sure. It might not matter.
10349 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010350 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010351 }
10352 }
10353
10354 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010355 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010356 QualType FieldType = Context.getBaseElementType(F->getType());
10357 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10358 CXXConstructorDecl *Constructor =
10359 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010360 // If this is a deleted function, add it anyway. This might be conformant
10361 // with the standard. This might not. I'm not sure. It might not matter.
10362 // In particular, the problem is that this function never gets called. It
10363 // might just be ill-formed because this function attempts to refer to
10364 // a deleted function here.
10365 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010366 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010367 }
10368 }
10369
10370 return ExceptSpec;
10371}
10372
10373CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10374 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010375 assert(ClassDecl->needsImplicitMoveConstructor());
10376
Richard Smith8bf22e52012-11-29 01:34:07 +000010377 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10378 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010379 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010380
Sebastian Redl22653ba2011-08-30 19:58:05 +000010381 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10382 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010383
Richard Smithb5800092012-06-10 05:43:50 +000010384 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10385 CXXMoveConstructor,
10386 false);
10387
Sebastian Redl22653ba2011-08-30 19:58:05 +000010388 DeclarationName Name
10389 = Context.DeclarationNames.getCXXConstructorName(
10390 Context.getCanonicalType(ClassType));
10391 SourceLocation ClassLoc = ClassDecl->getLocation();
10392 DeclarationNameInfo NameInfo(Name, ClassLoc);
10393
Richard Smith99005e62013-05-07 03:19:20 +000010394 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010395 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010396 // member of its class.
10397 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010398 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010399 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010400 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010401 MoveConstructor->setAccess(AS_public);
10402 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010403
Richard Smithd3b5c9082012-07-27 04:22:15 +000010404 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010405 FunctionProtoType::ExtProtoInfo EPI =
10406 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010407 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010408 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010409
Sebastian Redl22653ba2011-08-30 19:58:05 +000010410 // Add the parameter to the constructor.
10411 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10412 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010413 /*IdentifierInfo=*/nullptr,
10414 ArgType, /*TInfo=*/nullptr,
10415 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010416 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010417
Richard Smith6b02d462012-12-08 08:32:28 +000010418 MoveConstructor->setTrivial(
10419 ClassDecl->needsOverloadResolutionForMoveConstructor()
10420 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10421 : ClassDecl->hasTrivialMoveConstructor());
10422
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010423 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010424 ClassDecl->setImplicitMoveConstructorIsDeleted();
10425 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010426 }
10427
10428 // Note that we have declared this constructor.
10429 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10430
10431 if (Scope *S = getScopeForContext(ClassDecl))
10432 PushOnScopeChains(MoveConstructor, S, false);
10433 ClassDecl->addDecl(MoveConstructor);
10434
10435 return MoveConstructor;
10436}
10437
10438void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10439 CXXConstructorDecl *MoveConstructor) {
10440 assert((MoveConstructor->isDefaulted() &&
10441 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010442 !MoveConstructor->doesThisDeclarationHaveABody() &&
10443 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010444 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10445
10446 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10447 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10448
Eli Friedmaneaf34142012-10-18 20:14:08 +000010449 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010450 DiagnosticErrorTrap Trap(Diags);
10451
David Blaikie3fc2f912013-01-17 05:26:25 +000010452 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010453 Trap.hasErrorOccurred()) {
10454 Diag(CurrentLocation, diag::note_member_synthesized_at)
10455 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10456 MoveConstructor->setInvalidDecl();
10457 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010458 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10459 ? MoveConstructor->getLocEnd()
10460 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010461 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010462 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010463 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010464 }
10465
Eli Friedman276dd182013-09-05 00:02:25 +000010466 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010467
10468 if (ASTMutationListener *L = getASTMutationListener()) {
10469 L->CompletedImplicitDefinition(MoveConstructor);
10470 }
10471}
10472
Douglas Gregor74f7d502012-02-15 19:33:52 +000010473bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010474 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010475}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010476
10477void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010478 SourceLocation CurrentLocation,
10479 CXXConversionDecl *Conv) {
10480 CXXRecordDecl *Lambda = Conv->getParent();
10481 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10482 // If we are defining a specialization of a conversion to function-ptr
10483 // cache the deduced template arguments for this specialization
10484 // so that we can use them to retrieve the corresponding call-operator
10485 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010486 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10487
Faisal Vali571df122013-09-29 08:45:24 +000010488 // Retrieve the corresponding call-operator specialization.
10489 if (Lambda->isGenericLambda()) {
10490 assert(Conv->isFunctionTemplateSpecialization());
10491 FunctionTemplateDecl *CallOpTemplate =
10492 CallOp->getDescribedFunctionTemplate();
10493 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010494 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010495 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10496 DeducedTemplateArgs->data(),
10497 DeducedTemplateArgs->size(),
10498 InsertPos);
10499 assert(CallOpSpec &&
10500 "Conversion operator must have a corresponding call operator");
10501 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10502 }
10503 // Mark the call operator referenced (and add to pending instantiations
10504 // if necessary).
10505 // For both the conversion and static-invoker template specializations
10506 // we construct their body's in this function, so no need to add them
10507 // to the PendingInstantiations.
10508 MarkFunctionReferenced(CurrentLocation, CallOp);
10509
Eli Friedmaneaf34142012-10-18 20:14:08 +000010510 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010511 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010512
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010513 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010514 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10515 // ... and get the corresponding specialization for a generic lambda.
10516 if (Lambda->isGenericLambda()) {
10517 assert(DeducedTemplateArgs &&
10518 "Must have deduced template arguments from Conversion Operator");
10519 FunctionTemplateDecl *InvokeTemplate =
10520 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010521 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010522 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10523 DeducedTemplateArgs->data(),
10524 DeducedTemplateArgs->size(),
10525 InsertPos);
10526 assert(InvokeSpec &&
10527 "Must have a corresponding static invoker specialization");
10528 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10529 }
10530 // Construct the body of the conversion function { return __invoke; }.
10531 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010532 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010533 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010534 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010535 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10536 Conv->getLocation(),
10537 Conv->getLocation()));
10538
10539 Conv->markUsed(Context);
10540 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010541
Faisal Vali571df122013-09-29 08:45:24 +000010542 // Fill in the __invoke function with a dummy implementation. IR generation
10543 // will fill in the actual details.
10544 Invoker->markUsed(Context);
10545 Invoker->setReferenced();
10546 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10547
Douglas Gregord3b672c2012-02-16 01:06:16 +000010548 if (ASTMutationListener *L = getASTMutationListener()) {
10549 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010550 L->CompletedImplicitDefinition(Invoker);
10551 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010552}
10553
Faisal Vali571df122013-09-29 08:45:24 +000010554
10555
Douglas Gregord3b672c2012-02-16 01:06:16 +000010556void Sema::DefineImplicitLambdaToBlockPointerConversion(
10557 SourceLocation CurrentLocation,
10558 CXXConversionDecl *Conv)
10559{
Faisal Vali850da1a2013-09-29 17:08:32 +000010560 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010561
Eli Friedman276dd182013-09-05 00:02:25 +000010562 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010563
Eli Friedmaneaf34142012-10-18 20:14:08 +000010564 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010565 DiagnosticErrorTrap Trap(Diags);
10566
Douglas Gregored90df32012-02-22 05:02:47 +000010567 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010568 Expr *This = ActOnCXXThis(CurrentLocation).get();
10569 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010570
Eli Friedman98b01ed2012-03-01 04:01:32 +000010571 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10572 Conv->getLocation(),
10573 Conv, DerefThis);
10574
10575 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10576 // behavior. Note that only the general conversion function does this
10577 // (since it's unusable otherwise); in the case where we inline the
10578 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010579 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010580 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10581 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010582 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010583
10584 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010585 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010586 Conv->setInvalidDecl();
10587 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010588 }
Douglas Gregored90df32012-02-22 05:02:47 +000010589
Douglas Gregored90df32012-02-22 05:02:47 +000010590 // Create the return statement that returns the block from the conversion
10591 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010592 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010593 if (Return.isInvalid()) {
10594 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10595 Conv->setInvalidDecl();
10596 return;
10597 }
10598
10599 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010600 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000010601 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010602 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010603 Conv->getLocation()));
10604
Douglas Gregored90df32012-02-22 05:02:47 +000010605 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010606 if (ASTMutationListener *L = getASTMutationListener()) {
10607 L->CompletedImplicitDefinition(Conv);
10608 }
10609}
10610
Douglas Gregord2f70072012-03-10 06:53:13 +000010611/// \brief Determine whether the given list arguments contains exactly one
10612/// "real" (non-default) argument.
10613static bool hasOneRealArgument(MultiExprArg Args) {
10614 switch (Args.size()) {
10615 case 0:
10616 return false;
10617
10618 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010619 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010620 return false;
10621
10622 // fall through
10623 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010624 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010625 }
10626
10627 return false;
10628}
10629
John McCalldadc5752010-08-24 06:29:42 +000010630ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010631Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010632 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010633 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010634 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010635 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010636 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010637 unsigned ConstructKind,
10638 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010639 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010640
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010641 // C++0x [class.copy]p34:
10642 // When certain criteria are met, an implementation is allowed to
10643 // omit the copy/move construction of a class object, even if the
10644 // copy/move constructor and/or destructor for the object have
10645 // side effects. [...]
10646 // - when a temporary class object that has not been bound to a
10647 // reference (12.2) would be copied/moved to a class object
10648 // with the same cv-unqualified type, the copy/move operation
10649 // can be omitted by constructing the temporary object
10650 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010651 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010652 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010653 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010654 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010655 }
Mike Stump11289f42009-09-09 15:08:12 +000010656
10657 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010658 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010659 IsListInitialization, RequiresZeroInit,
10660 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010661}
10662
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010663/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10664/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010665ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010666Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10667 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010668 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010669 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010670 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010671 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010672 unsigned ConstructKind,
10673 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010674 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010675 return CXXConstructExpr::Create(
10676 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10677 HadMultipleCandidates, IsListInitialization, RequiresZeroInit,
10678 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10679 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010680}
10681
John McCall03c48482010-02-02 09:10:11 +000010682void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010683 if (VD->isInvalidDecl()) return;
10684
John McCall03c48482010-02-02 09:10:11 +000010685 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010686 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010687 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010688 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010689
Chandler Carruth86d17d32011-03-27 21:26:48 +000010690 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010691 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010692 CheckDestructorAccess(VD->getLocation(), Destructor,
10693 PDiag(diag::err_access_dtor_var)
10694 << VD->getDeclName()
10695 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010696 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010697
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010698 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010699 if (!VD->hasGlobalStorage()) return;
10700
10701 // Emit warning for non-trivial dtor in global scope (a real global,
10702 // class-static, function-static).
10703 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10704
10705 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010706 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010707 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010708}
10709
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010710/// \brief Given a constructor and the set of arguments provided for the
10711/// constructor, convert the arguments and add any required default arguments
10712/// to form a proper call to this constructor.
10713///
10714/// \returns true if an error occurred, false otherwise.
10715bool
10716Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10717 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010718 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010719 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010720 bool AllowExplicit,
10721 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010722 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10723 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010724 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010725
10726 const FunctionProtoType *Proto
10727 = Constructor->getType()->getAs<FunctionProtoType>();
10728 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010729 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010730
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010731 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010732 if (NumArgs < NumParams)
10733 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010734 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010735 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010736
10737 VariadicCallType CallType =
10738 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010739 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010740 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010741 Proto, 0,
10742 llvm::makeArrayRef(Args, NumArgs),
10743 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010744 CallType, AllowExplicit,
10745 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010746 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010747
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010748 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010749
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010750 CheckConstructorCall(Constructor,
10751 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10752 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010753 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010754
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010755 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010756}
10757
Anders Carlssone363c8e2009-12-12 00:32:00 +000010758static inline bool
10759CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10760 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010761 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010762 if (isa<NamespaceDecl>(DC)) {
10763 return SemaRef.Diag(FnDecl->getLocation(),
10764 diag::err_operator_new_delete_declared_in_namespace)
10765 << FnDecl->getDeclName();
10766 }
10767
10768 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010769 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010770 return SemaRef.Diag(FnDecl->getLocation(),
10771 diag::err_operator_new_delete_declared_static)
10772 << FnDecl->getDeclName();
10773 }
10774
Anders Carlsson60659a82009-12-12 02:43:16 +000010775 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010776}
10777
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010778static inline bool
10779CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10780 CanQualType ExpectedResultType,
10781 CanQualType ExpectedFirstParamType,
10782 unsigned DependentParamTypeDiag,
10783 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010784 QualType ResultType =
10785 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010786
10787 // Check that the result type is not dependent.
10788 if (ResultType->isDependentType())
10789 return SemaRef.Diag(FnDecl->getLocation(),
10790 diag::err_operator_new_delete_dependent_result_type)
10791 << FnDecl->getDeclName() << ExpectedResultType;
10792
10793 // Check that the result type is what we expect.
10794 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10795 return SemaRef.Diag(FnDecl->getLocation(),
10796 diag::err_operator_new_delete_invalid_result_type)
10797 << FnDecl->getDeclName() << ExpectedResultType;
10798
10799 // A function template must have at least 2 parameters.
10800 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10801 return SemaRef.Diag(FnDecl->getLocation(),
10802 diag::err_operator_new_delete_template_too_few_parameters)
10803 << FnDecl->getDeclName();
10804
10805 // The function decl must have at least 1 parameter.
10806 if (FnDecl->getNumParams() == 0)
10807 return SemaRef.Diag(FnDecl->getLocation(),
10808 diag::err_operator_new_delete_too_few_parameters)
10809 << FnDecl->getDeclName();
10810
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010811 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010812 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10813 if (FirstParamType->isDependentType())
10814 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10815 << FnDecl->getDeclName() << ExpectedFirstParamType;
10816
10817 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010818 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010819 ExpectedFirstParamType)
10820 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10821 << FnDecl->getDeclName() << ExpectedFirstParamType;
10822
10823 return false;
10824}
10825
Anders Carlsson12308f42009-12-11 23:23:22 +000010826static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010827CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010828 // C++ [basic.stc.dynamic.allocation]p1:
10829 // A program is ill-formed if an allocation function is declared in a
10830 // namespace scope other than global scope or declared static in global
10831 // scope.
10832 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10833 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010834
10835 CanQualType SizeTy =
10836 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10837
10838 // C++ [basic.stc.dynamic.allocation]p1:
10839 // The return type shall be void*. The first parameter shall have type
10840 // std::size_t.
10841 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10842 SizeTy,
10843 diag::err_operator_new_dependent_param_type,
10844 diag::err_operator_new_param_type))
10845 return true;
10846
10847 // C++ [basic.stc.dynamic.allocation]p1:
10848 // The first parameter shall not have an associated default argument.
10849 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010850 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010851 diag::err_operator_new_default_arg)
10852 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10853
10854 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010855}
10856
10857static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010858CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010859 // C++ [basic.stc.dynamic.deallocation]p1:
10860 // A program is ill-formed if deallocation functions are declared in a
10861 // namespace scope other than global scope or declared static in global
10862 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010863 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10864 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010865
10866 // C++ [basic.stc.dynamic.deallocation]p2:
10867 // Each deallocation function shall return void and its first parameter
10868 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010869 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10870 SemaRef.Context.VoidPtrTy,
10871 diag::err_operator_delete_dependent_param_type,
10872 diag::err_operator_delete_param_type))
10873 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010874
Anders Carlsson12308f42009-12-11 23:23:22 +000010875 return false;
10876}
10877
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010878/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10879/// of this overloaded operator is well-formed. If so, returns false;
10880/// otherwise, emits appropriate diagnostics and returns true.
10881bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010882 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010883 "Expected an overloaded operator declaration");
10884
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010885 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10886
Mike Stump11289f42009-09-09 15:08:12 +000010887 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010888 // The allocation and deallocation functions, operator new,
10889 // operator new[], operator delete and operator delete[], are
10890 // described completely in 3.7.3. The attributes and restrictions
10891 // found in the rest of this subclause do not apply to them unless
10892 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010893 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010894 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010895
Anders Carlsson22f443f2009-12-12 00:26:23 +000010896 if (Op == OO_New || Op == OO_Array_New)
10897 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010898
10899 // C++ [over.oper]p6:
10900 // An operator function shall either be a non-static member
10901 // function or be a non-member function and have at least one
10902 // parameter whose type is a class, a reference to a class, an
10903 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010904 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10905 if (MethodDecl->isStatic())
10906 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010907 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010908 } else {
10909 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010910 for (auto Param : FnDecl->params()) {
10911 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010912 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10913 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010914 ClassOrEnumParam = true;
10915 break;
10916 }
10917 }
10918
Douglas Gregord69246b2008-11-17 16:14:12 +000010919 if (!ClassOrEnumParam)
10920 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010921 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010922 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010923 }
10924
10925 // C++ [over.oper]p8:
10926 // An operator function cannot have default arguments (8.3.6),
10927 // except where explicitly stated below.
10928 //
Mike Stump11289f42009-09-09 15:08:12 +000010929 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010930 // (C++ [over.call]p1).
10931 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010932 for (auto Param : FnDecl->params()) {
10933 if (Param->hasDefaultArg())
10934 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010935 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010936 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010937 }
10938 }
10939
Douglas Gregor6cf08062008-11-10 13:38:07 +000010940 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10941 { false, false, false }
10942#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10943 , { Unary, Binary, MemberOnly }
10944#include "clang/Basic/OperatorKinds.def"
10945 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010946
Douglas Gregor6cf08062008-11-10 13:38:07 +000010947 bool CanBeUnaryOperator = OperatorUses[Op][0];
10948 bool CanBeBinaryOperator = OperatorUses[Op][1];
10949 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010950
10951 // C++ [over.oper]p8:
10952 // [...] Operator functions cannot have more or fewer parameters
10953 // than the number required for the corresponding operator, as
10954 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010955 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010956 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010957 if (Op != OO_Call &&
10958 ((NumParams == 1 && !CanBeUnaryOperator) ||
10959 (NumParams == 2 && !CanBeBinaryOperator) ||
10960 (NumParams < 1) || (NumParams > 2))) {
10961 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010962 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010963 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010964 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010965 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010966 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010967 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010968 assert(CanBeBinaryOperator &&
10969 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010970 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010971 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010972
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010973 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010974 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010975 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010976
Douglas Gregord69246b2008-11-17 16:14:12 +000010977 // Overloaded operators other than operator() cannot be variadic.
10978 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010979 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010980 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010981 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010982 }
10983
10984 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010985 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10986 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010987 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010988 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010989 }
10990
10991 // C++ [over.inc]p1:
10992 // The user-defined function called operator++ implements the
10993 // prefix and postfix ++ operator. If this function is a member
10994 // function with no parameters, or a non-member function with one
10995 // parameter of class or enumeration type, it defines the prefix
10996 // increment operator ++ for objects of that type. If the function
10997 // is a member function with one parameter (which shall be of type
10998 // int) or a non-member function with two parameters (the second
10999 // of which shall be of type int), it defines the postfix
11000 // increment operator ++ for objects of that type.
11001 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11002 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011003 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011004
Richard Smith538b52a2014-01-30 22:24:05 +000011005 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11006 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011007 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011008 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011009 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011010 }
11011
Douglas Gregord69246b2008-11-17 16:14:12 +000011012 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011013}
Chris Lattner3b024a32008-12-17 07:09:26 +000011014
Alexis Huntc88db062010-01-13 09:01:02 +000011015/// CheckLiteralOperatorDeclaration - Check whether the declaration
11016/// of this literal operator function is well-formed. If so, returns
11017/// false; otherwise, emits appropriate diagnostics and returns true.
11018bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011019 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011020 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11021 << FnDecl->getDeclName();
11022 return true;
11023 }
11024
Richard Smith72eebee2012-03-04 09:41:16 +000011025 if (FnDecl->isExternC()) {
11026 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11027 return true;
11028 }
11029
Alexis Huntc88db062010-01-13 09:01:02 +000011030 bool Valid = false;
11031
Richard Smithbcc22fc2012-03-09 08:00:36 +000011032 // This might be the definition of a literal operator template.
11033 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11034 // This might be a specialization of a literal operator template.
11035 if (!TpDecl)
11036 TpDecl = FnDecl->getPrimaryTemplate();
11037
Richard Smithb8b41d32013-10-07 19:57:58 +000011038 // template <char...> type operator "" name() and
11039 // template <class T, T...> type operator "" name() are the only valid
11040 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011041 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011042 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011043 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011044 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11045 if (Params->size() == 1) {
11046 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011047 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011048
Alexis Hunt7dd26172010-04-07 23:11:06 +000011049 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011050 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11051 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11052 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011053 } else if (Params->size() == 2) {
11054 TemplateTypeParmDecl *PmType =
11055 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11056 NonTypeTemplateParmDecl *PmArgs =
11057 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11058
11059 // The second template parameter must be a parameter pack with the
11060 // first template parameter as its type.
11061 if (PmType && PmArgs &&
11062 !PmType->isTemplateParameterPack() &&
11063 PmArgs->isTemplateParameterPack()) {
11064 const TemplateTypeParmType *TArgs =
11065 PmArgs->getType()->getAs<TemplateTypeParmType>();
11066 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11067 TArgs->getIndex() == PmType->getIndex()) {
11068 Valid = true;
11069 if (ActiveTemplateInstantiations.empty())
11070 Diag(FnDecl->getLocation(),
11071 diag::ext_string_literal_operator_template);
11072 }
11073 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011074 }
11075 }
Richard Smith72eebee2012-03-04 09:41:16 +000011076 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011077 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011078 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11079
Richard Smith72eebee2012-03-04 09:41:16 +000011080 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011081
Alexis Hunt079a6f72010-04-07 22:57:35 +000011082 // unsigned long long int, long double, and any character type are allowed
11083 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011084 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11085 Context.hasSameType(T, Context.LongDoubleTy) ||
11086 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011087 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011088 Context.hasSameType(T, Context.Char16Ty) ||
11089 Context.hasSameType(T, Context.Char32Ty)) {
11090 if (++Param == FnDecl->param_end())
11091 Valid = true;
11092 goto FinishedParams;
11093 }
11094
Alexis Hunt079a6f72010-04-07 22:57:35 +000011095 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011096 const PointerType *PT = T->getAs<PointerType>();
11097 if (!PT)
11098 goto FinishedParams;
11099 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011100 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011101 goto FinishedParams;
11102 T = T.getUnqualifiedType();
11103
11104 // Move on to the second parameter;
11105 ++Param;
11106
11107 // If there is no second parameter, the first must be a const char *
11108 if (Param == FnDecl->param_end()) {
11109 if (Context.hasSameType(T, Context.CharTy))
11110 Valid = true;
11111 goto FinishedParams;
11112 }
11113
11114 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11115 // are allowed as the first parameter to a two-parameter function
11116 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011117 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011118 Context.hasSameType(T, Context.Char16Ty) ||
11119 Context.hasSameType(T, Context.Char32Ty)))
11120 goto FinishedParams;
11121
11122 // The second and final parameter must be an std::size_t
11123 T = (*Param)->getType().getUnqualifiedType();
11124 if (Context.hasSameType(T, Context.getSizeType()) &&
11125 ++Param == FnDecl->param_end())
11126 Valid = true;
11127 }
11128
11129 // FIXME: This diagnostic is absolutely terrible.
11130FinishedParams:
11131 if (!Valid) {
11132 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11133 << FnDecl->getDeclName();
11134 return true;
11135 }
11136
Richard Smith768cecc2012-03-09 08:16:22 +000011137 // A parameter-declaration-clause containing a default argument is not
11138 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011139 for (auto Param : FnDecl->params()) {
11140 if (Param->hasDefaultArg()) {
11141 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011142 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011143 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011144 break;
11145 }
11146 }
11147
Richard Smith0df56f42012-03-08 02:39:21 +000011148 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011149 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11150 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011151 // C++11 [usrlit.suffix]p1:
11152 // Literal suffix identifiers that do not start with an underscore
11153 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011154 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11155 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011156 }
Richard Smith0df56f42012-03-08 02:39:21 +000011157
Alexis Huntc88db062010-01-13 09:01:02 +000011158 return false;
11159}
11160
Douglas Gregor07665a62009-01-05 19:45:36 +000011161/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11162/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011163/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11164/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011165/// the '{' brace. Otherwise, this linkage specification does not
11166/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011167Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011168 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011169 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011170 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11171 if (!Lit->isAscii()) {
11172 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11173 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011174 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011175 }
11176
11177 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011178 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011179 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011180 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011181 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011182 Language = LinkageSpecDecl::lang_cxx;
11183 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011184 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11185 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011186 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011187 }
Mike Stump11289f42009-09-09 15:08:12 +000011188
Chris Lattner438e5012008-12-17 07:13:27 +000011189 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011190
Richard Smith4ee696d2014-02-17 23:25:27 +000011191 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11192 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011193 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011194 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011195 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011196 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011197}
11198
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011199/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011200/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11201/// valid, it's the position of the closing '}' brace in a linkage
11202/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011203Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011204 Decl *LinkageSpec,
11205 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011206 if (RBraceLoc.isValid()) {
11207 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11208 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011209 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011210 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011211 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011212}
11213
Michael Han84324352013-02-22 17:15:32 +000011214Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11215 AttributeList *AttrList,
11216 SourceLocation SemiLoc) {
11217 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11218 // Attribute declarations appertain to empty declaration so we handle
11219 // them here.
11220 if (AttrList)
11221 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011222
Michael Han84324352013-02-22 17:15:32 +000011223 CurContext->addDecl(ED);
11224 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011225}
11226
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011227/// \brief Perform semantic analysis for the variable declaration that
11228/// occurs within a C++ catch clause, returning the newly-created
11229/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011230VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011231 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011232 SourceLocation StartLoc,
11233 SourceLocation Loc,
11234 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011235 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011236 QualType ExDeclType = TInfo->getType();
11237
Sebastian Redl54c04d42008-12-22 19:15:10 +000011238 // Arrays and functions decay.
11239 if (ExDeclType->isArrayType())
11240 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11241 else if (ExDeclType->isFunctionType())
11242 ExDeclType = Context.getPointerType(ExDeclType);
11243
11244 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11245 // The exception-declaration shall not denote a pointer or reference to an
11246 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011247 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011248 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011249 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011250 Invalid = true;
11251 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011252
Sebastian Redl54c04d42008-12-22 19:15:10 +000011253 QualType BaseType = ExDeclType;
11254 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011255 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011256 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011257 BaseType = Ptr->getPointeeType();
11258 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011259 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011260 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011261 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011262 BaseType = Ref->getPointeeType();
11263 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011264 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011265 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011266 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011267 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011268 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011269
Mike Stump11289f42009-09-09 15:08:12 +000011270 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011271 RequireNonAbstractType(Loc, ExDeclType,
11272 diag::err_abstract_type_in_decl,
11273 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011274 Invalid = true;
11275
John McCall2ca705e2010-07-24 00:37:23 +000011276 // Only the non-fragile NeXT runtime currently supports C++ catches
11277 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011278 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011279 QualType T = ExDeclType;
11280 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11281 T = RT->getPointeeType();
11282
11283 if (T->isObjCObjectType()) {
11284 Diag(Loc, diag::err_objc_object_catch);
11285 Invalid = true;
11286 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011287 // FIXME: should this be a test for macosx-fragile specifically?
11288 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011289 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011290 }
11291 }
11292
Abramo Bagnaradff19302011-03-08 08:55:46 +000011293 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011294 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011295 ExDecl->setExceptionVariable(true);
11296
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011297 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011298 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011299 Invalid = true;
11300
Douglas Gregor750734c2011-07-06 18:14:43 +000011301 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011302 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011303 // Insulate this from anything else we might currently be parsing.
11304 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11305
Douglas Gregor6de584c2010-03-05 23:38:39 +000011306 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011307 // The object declared in an exception-declaration or, if the
11308 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011309 // copy-initialized (8.5) from the exception object. [...]
11310 // The object is destroyed when the handler exits, after the destruction
11311 // of any automatic objects initialized within the handler.
11312 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011313 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011314 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011315 QualType initType = ExDeclType;
11316
11317 InitializedEntity entity =
11318 InitializedEntity::InitializeVariable(ExDecl);
11319 InitializationKind initKind =
11320 InitializationKind::CreateCopy(Loc, SourceLocation());
11321
11322 Expr *opaqueValue =
11323 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011324 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11325 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011326 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011327 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011328 else {
11329 // If the constructor used was non-trivial, set this as the
11330 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011331 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011332 if (!construct->getConstructor()->isTrivial()) {
11333 Expr *init = MaybeCreateExprWithCleanups(construct);
11334 ExDecl->setInit(init);
11335 }
11336
11337 // And make sure it's destructable.
11338 FinalizeVarWithDestructor(ExDecl, recordType);
11339 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011340 }
11341 }
11342
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011343 if (Invalid)
11344 ExDecl->setInvalidDecl();
11345
11346 return ExDecl;
11347}
11348
11349/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11350/// handler.
John McCall48871652010-08-21 09:40:31 +000011351Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011352 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011353 bool Invalid = D.isInvalidType();
11354
11355 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011356 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11357 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011358 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11359 D.getIdentifierLoc());
11360 Invalid = true;
11361 }
11362
Sebastian Redl54c04d42008-12-22 19:15:10 +000011363 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011364 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011365 LookupOrdinaryName,
11366 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011367 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011368 // it contains any previous declaration, except for function parameters in
11369 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011370 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011371 if (isDeclInScope(PrevDecl, CurContext, S)) {
11372 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11373 << D.getIdentifier();
11374 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11375 Invalid = true;
11376 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011377 // Maybe we will complain about the shadowed template parameter.
11378 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011379 }
11380
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011381 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011382 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11383 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011384 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011385 }
11386
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011387 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011388 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011389 D.getIdentifierLoc(),
11390 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011391 if (Invalid)
11392 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011393
Sebastian Redl54c04d42008-12-22 19:15:10 +000011394 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011395 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011396 PushOnScopeChains(ExDecl, S);
11397 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011398 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011399
Douglas Gregor758a8692009-06-17 21:51:59 +000011400 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011401 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011402}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011403
Abramo Bagnaraea947882011-03-08 16:41:52 +000011404Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011405 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011406 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011407 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011408 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011409
Richard Smithded9c2e2012-07-11 22:37:56 +000011410 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011411 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011412
11413 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11414 AssertMessage, RParenLoc, false);
11415}
11416
11417Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11418 Expr *AssertExpr,
11419 StringLiteral *AssertMessage,
11420 SourceLocation RParenLoc,
11421 bool Failed) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000011422 assert(AssertExpr != nullptr && AssertMessage != nullptr &&
11423 "Expected non-null Expr's");
Richard Smithded9c2e2012-07-11 22:37:56 +000011424 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11425 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011426 // In a static_assert-declaration, the constant-expression shall be a
11427 // constant expression that can be contextually converted to bool.
11428 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11429 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011430 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011431
Richard Smith902ca212011-12-14 23:32:26 +000011432 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011433 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011434 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011435 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011436 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011437
Richard Smithded9c2e2012-07-11 22:37:56 +000011438 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011439 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011440 llvm::raw_svector_ostream Msg(MsgBuffer);
Craig Topperc3ec1492014-05-26 06:22:03 +000011441 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011442 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011443 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011444 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011445 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011446 }
Mike Stump11289f42009-09-09 15:08:12 +000011447
Abramo Bagnaraea947882011-03-08 16:41:52 +000011448 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011449 AssertExpr, AssertMessage, RParenLoc,
11450 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011451
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011452 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011453 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011454}
Sebastian Redlf769df52009-03-24 22:27:57 +000011455
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011456/// \brief Perform semantic analysis of the given friend type declaration.
11457///
11458/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011459FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011460 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011461 TypeSourceInfo *TSInfo) {
11462 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11463
11464 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011465 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011466
Richard Smithc8239732011-10-18 21:39:00 +000011467 // C++03 [class.friend]p2:
11468 // An elaborated-type-specifier shall be used in a friend declaration
11469 // for a class.*
11470 //
11471 // * The class-key of the elaborated-type-specifier is required.
11472 if (!ActiveTemplateInstantiations.empty()) {
11473 // Do not complain about the form of friend template types during
11474 // template instantiation; we will already have complained when the
11475 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011476 } else {
11477 if (!T->isElaboratedTypeSpecifier()) {
11478 // If we evaluated the type to a record type, suggest putting
11479 // a tag in front.
11480 if (const RecordType *RT = T->getAs<RecordType>()) {
11481 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011482
11483 SmallString<16> InsertionText(" ");
11484 InsertionText += RD->getKindName();
11485
Nick Lewycky36722d22013-02-06 05:59:33 +000011486 Diag(TypeRange.getBegin(),
11487 getLangOpts().CPlusPlus11 ?
11488 diag::warn_cxx98_compat_unelaborated_friend_type :
11489 diag::ext_unelaborated_friend_type)
11490 << (unsigned) RD->getTagKind()
11491 << T
11492 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11493 InsertionText);
11494 } else {
11495 Diag(FriendLoc,
11496 getLangOpts().CPlusPlus11 ?
11497 diag::warn_cxx98_compat_nonclass_type_friend :
11498 diag::ext_nonclass_type_friend)
11499 << T
11500 << TypeRange;
11501 }
11502 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011503 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011504 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011505 diag::warn_cxx98_compat_enum_friend :
11506 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011507 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011508 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011509 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011510
Nick Lewycky36722d22013-02-06 05:59:33 +000011511 // C++11 [class.friend]p3:
11512 // A friend declaration that does not declare a function shall have one
11513 // of the following forms:
11514 // friend elaborated-type-specifier ;
11515 // friend simple-type-specifier ;
11516 // friend typename-specifier ;
11517 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11518 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11519 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011520
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011521 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011522 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011523 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011524 return FriendDecl::Create(Context, CurContext,
11525 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11526 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011527}
11528
John McCallace48cd2010-10-19 01:40:49 +000011529/// Handle a friend tag declaration where the scope specifier was
11530/// templated.
11531Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11532 unsigned TagSpec, SourceLocation TagLoc,
11533 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011534 IdentifierInfo *Name,
11535 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011536 AttributeList *Attr,
11537 MultiTemplateParamsArg TempParamLists) {
11538 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11539
11540 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011541 bool Invalid = false;
11542
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011543 if (TemplateParameterList *TemplateParams =
11544 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011545 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011546 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011547 if (TemplateParams->size() > 0) {
11548 // This is a declaration of a class template.
11549 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011550 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011551
Eric Christopher6f228b52011-07-21 05:34:24 +000011552 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11553 SS, Name, NameLoc, Attr,
11554 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011555 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011556 TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011557 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011558 } else {
11559 // The "template<>" header is extraneous.
11560 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11561 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11562 isExplicitSpecialization = true;
11563 }
11564 }
11565
Craig Topperc3ec1492014-05-26 06:22:03 +000011566 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011567
John McCallace48cd2010-10-19 01:40:49 +000011568 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011569 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011570 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011571 isAllExplicitSpecializations = false;
11572 break;
11573 }
11574 }
11575
11576 // FIXME: don't ignore attributes.
11577
11578 // If it's explicit specializations all the way down, just forget
11579 // about the template header and build an appropriate non-templated
11580 // friend. TODO: for source fidelity, remember the headers.
11581 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011582 if (SS.isEmpty()) {
11583 bool Owned = false;
11584 bool IsDependent = false;
11585 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011586 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011587 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011588 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011589 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011590 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011591 /*UnderlyingType=*/TypeResult(),
11592 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011593 }
Richard Smith649c7b062014-01-08 00:56:48 +000011594
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011595 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011596 ElaboratedTypeKeyword Keyword
11597 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011598 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011599 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011600 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000011601 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011602
11603 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11604 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011605 DependentNameTypeLoc TL =
11606 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011607 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011608 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011609 TL.setNameLoc(NameLoc);
11610 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011611 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011612 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011613 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011614 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011615 }
11616
11617 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011618 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011619 Friend->setAccess(AS_public);
11620 CurContext->addDecl(Friend);
11621 return Friend;
11622 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011623
11624 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11625
11626
John McCallace48cd2010-10-19 01:40:49 +000011627
11628 // Handle the case of a templated-scope friend class. e.g.
11629 // template <class T> class A<T>::B;
11630 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011631 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11632 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011633 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11634 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11635 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011636 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011637 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011638 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011639 TL.setNameLoc(NameLoc);
11640
11641 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011642 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011643 Friend->setAccess(AS_public);
11644 Friend->setUnsupportedFriend(true);
11645 CurContext->addDecl(Friend);
11646 return Friend;
11647}
11648
11649
John McCall11083da2009-09-16 22:47:08 +000011650/// Handle a friend type declaration. This works in tandem with
11651/// ActOnTag.
11652///
11653/// Notes on friend class templates:
11654///
11655/// We generally treat friend class declarations as if they were
11656/// declaring a class. So, for example, the elaborated type specifier
11657/// in a friend declaration is required to obey the restrictions of a
11658/// class-head (i.e. no typedefs in the scope chain), template
11659/// parameters are required to match up with simple template-ids, &c.
11660/// However, unlike when declaring a template specialization, it's
11661/// okay to refer to a template specialization without an empty
11662/// template parameter declaration, e.g.
11663/// friend class A<T>::B<unsigned>;
11664/// We permit this as a special case; if there are any template
11665/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011666/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011667Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011668 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011669 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011670
11671 assert(DS.isFriendSpecified());
11672 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11673
John McCall11083da2009-09-16 22:47:08 +000011674 // Try to convert the decl specifier to a type. This works for
11675 // friend templates because ActOnTag never produces a ClassTemplateDecl
11676 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011677 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011678 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11679 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011680 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000011681 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011682
Douglas Gregor6c110f32010-12-16 01:14:37 +000011683 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011684 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011685
John McCall11083da2009-09-16 22:47:08 +000011686 // This is definitely an error in C++98. It's probably meant to
11687 // be forbidden in C++0x, too, but the specification is just
11688 // poorly written.
11689 //
11690 // The problem is with declarations like the following:
11691 // template <T> friend A<T>::foo;
11692 // where deciding whether a class C is a friend or not now hinges
11693 // on whether there exists an instantiation of A that causes
11694 // 'foo' to equal C. There are restrictions on class-heads
11695 // (which we declare (by fiat) elaborated friend declarations to
11696 // be) that makes this tractable.
11697 //
11698 // FIXME: handle "template <> friend class A<T>;", which
11699 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011700 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011701 Diag(Loc, diag::err_tagless_friend_type_template)
11702 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011703 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000011704 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011705
John McCallaa74a0c2009-08-28 07:59:38 +000011706 // C++98 [class.friend]p1: A friend of a class is a function
11707 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011708 // This is fixed in DR77, which just barely didn't make the C++03
11709 // deadline. It's also a very silly restriction that seriously
11710 // affects inner classes and which nobody else seems to implement;
11711 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011712 //
11713 // But note that we could warn about it: it's always useless to
11714 // friend one of your own members (it's not, however, worthless to
11715 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011716
John McCall11083da2009-09-16 22:47:08 +000011717 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011718 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011719 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011720 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011721 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011722 TSI,
John McCall11083da2009-09-16 22:47:08 +000011723 DS.getFriendSpecLoc());
11724 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011725 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011726
11727 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000011728 return nullptr;
11729
John McCall11083da2009-09-16 22:47:08 +000011730 D->setAccess(AS_public);
11731 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011732
John McCall48871652010-08-21 09:40:31 +000011733 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011734}
11735
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011736NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11737 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011738 const DeclSpec &DS = D.getDeclSpec();
11739
11740 assert(DS.isFriendSpecified());
11741 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11742
11743 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011744 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011745
11746 // C++ [class.friend]p1
11747 // A friend of a class is a function or class....
11748 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011749 // It *doesn't* see through dependent types, which is correct
11750 // according to [temp.arg.type]p3:
11751 // If a declaration acquires a function type through a
11752 // type dependent on a template-parameter and this causes
11753 // a declaration that does not use the syntactic form of a
11754 // function declarator to have a function type, the program
11755 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011756 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011757 Diag(Loc, diag::err_unexpected_friend);
11758
11759 // It might be worthwhile to try to recover by creating an
11760 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011761 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011762 }
11763
11764 // C++ [namespace.memdef]p3
11765 // - If a friend declaration in a non-local class first declares a
11766 // class or function, the friend class or function is a member
11767 // of the innermost enclosing namespace.
11768 // - The name of the friend is not found by simple name lookup
11769 // until a matching declaration is provided in that namespace
11770 // scope (either before or after the class declaration granting
11771 // friendship).
11772 // - If a friend function is called, its name may be found by the
11773 // name lookup that considers functions from namespaces and
11774 // classes associated with the types of the function arguments.
11775 // - When looking for a prior declaration of a class or a function
11776 // declared as a friend, scopes outside the innermost enclosing
11777 // namespace scope are not considered.
11778
John McCallde3fd222010-10-12 23:13:28 +000011779 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011780 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11781 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011782 assert(Name);
11783
Douglas Gregor6c110f32010-12-16 01:14:37 +000011784 // Check for unexpanded parameter packs.
11785 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11786 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11787 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011788 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011789
John McCall07e91c02009-08-06 02:15:43 +000011790 // The context we found the declaration in, or in which we should
11791 // create the declaration.
11792 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011793 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011794 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011795 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011796
Richard Smith114394f2013-08-09 04:35:01 +000011797 // There are five cases here.
11798 // - There's no scope specifier and we're in a local class. Only look
11799 // for functions declared in the immediately-enclosing block scope.
11800 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000011801 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000011802 if ((SS.isInvalid() || !SS.isSet()) &&
11803 (FunctionContainingLocalClass =
11804 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11805 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011806 // If a friend declaration appears in a local class and the name
11807 // specified is an unqualified name, a prior declaration is
11808 // looked up without considering scopes that are outside the
11809 // innermost enclosing non-class scope. For a friend function
11810 // declaration, if there is no prior declaration, the program is
11811 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011812
11813 // Find the innermost enclosing non-class scope. This is the block
11814 // scope containing the local class definition (or for a nested class,
11815 // the outer local class).
11816 DCScope = S->getFnParent();
11817
11818 // Look up the function name in the scope.
11819 Previous.clear(LookupLocalFriendName);
11820 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11821
11822 if (!Previous.empty()) {
11823 // All possible previous declarations must have the same context:
11824 // either they were declared at block scope or they are members of
11825 // one of the enclosing local classes.
11826 DC = Previous.getRepresentativeDecl()->getDeclContext();
11827 } else {
11828 // This is ill-formed, but provide the context that we would have
11829 // declared the function in, if we were permitted to, for error recovery.
11830 DC = FunctionContainingLocalClass;
11831 }
Richard Smith541b38b2013-09-20 01:15:31 +000011832 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011833
11834 // C++ [class.friend]p6:
11835 // A function can be defined in a friend declaration of a class if and
11836 // only if the class is a non-local class (9.8), the function name is
11837 // unqualified, and the function has namespace scope.
11838 if (D.isFunctionDefinition()) {
11839 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11840 }
11841
11842 // - There's no scope specifier, in which case we just go to the
11843 // appropriate scope and look for a function or function template
11844 // there as appropriate.
11845 } else if (SS.isInvalid() || !SS.isSet()) {
11846 // C++11 [namespace.memdef]p3:
11847 // If the name in a friend declaration is neither qualified nor
11848 // a template-id and the declaration is a function or an
11849 // elaborated-type-specifier, the lookup to determine whether
11850 // the entity has been previously declared shall not consider
11851 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011852 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011853
John McCallf7cfb222010-10-13 05:45:15 +000011854 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011855 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011856
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011857 // Skip class contexts. If someone can cite chapter and verse
11858 // for this behavior, that would be nice --- it's what GCC and
11859 // EDG do, and it seems like a reasonable intent, but the spec
11860 // really only says that checks for unqualified existing
11861 // declarations should stop at the nearest enclosing namespace,
11862 // not that they should only consider the nearest enclosing
11863 // namespace.
11864 while (DC->isRecord())
11865 DC = DC->getParent();
11866
11867 DeclContext *LookupDC = DC;
11868 while (LookupDC->isTransparentContext())
11869 LookupDC = LookupDC->getParent();
11870
11871 while (true) {
11872 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011873
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011874 if (!Previous.empty()) {
11875 DC = LookupDC;
11876 break;
John McCallf4776592010-10-14 22:22:28 +000011877 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011878
11879 if (isTemplateId) {
11880 if (isa<TranslationUnitDecl>(LookupDC)) break;
11881 } else {
11882 if (LookupDC->isFileContext()) break;
11883 }
11884 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011885 }
11886
John McCallccbc0322010-10-13 06:22:15 +000011887 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011888
John McCallde3fd222010-10-12 23:13:28 +000011889 // - There's a non-dependent scope specifier, in which case we
11890 // compute it and do a previous lookup there for a function
11891 // or function template.
11892 } else if (!SS.getScopeRep()->isDependent()) {
11893 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000011894 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011895
Craig Topperc3ec1492014-05-26 06:22:03 +000011896 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011897
11898 LookupQualifiedName(Previous, DC);
11899
11900 // Ignore things found implicitly in the wrong scope.
11901 // TODO: better diagnostics for this case. Suggesting the right
11902 // qualified scope would be nice...
11903 LookupResult::Filter F = Previous.makeFilter();
11904 while (F.hasNext()) {
11905 NamedDecl *D = F.next();
11906 if (!DC->InEnclosingNamespaceSetOf(
11907 D->getDeclContext()->getRedeclContext()))
11908 F.erase();
11909 }
11910 F.done();
11911
11912 if (Previous.empty()) {
11913 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011914 Diag(Loc, diag::err_qualified_friend_not_found)
11915 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000011916 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011917 }
11918
11919 // C++ [class.friend]p1: A friend of a class is a function or
11920 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011921 if (DC->Equals(CurContext))
11922 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011923 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011924 diag::warn_cxx98_compat_friend_is_member :
11925 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011926
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011927 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011928 // C++ [class.friend]p6:
11929 // A function can be defined in a friend declaration of a class if and
11930 // only if the class is a non-local class (9.8), the function name is
11931 // unqualified, and the function has namespace scope.
11932 SemaDiagnosticBuilder DB
11933 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11934
11935 DB << SS.getScopeRep();
11936 if (DC->isFileContext())
11937 DB << FixItHint::CreateRemoval(SS.getRange());
11938 SS.clear();
11939 }
John McCallde3fd222010-10-12 23:13:28 +000011940
11941 // - There's a scope specifier that does not match any template
11942 // parameter lists, in which case we use some arbitrary context,
11943 // create a method or method template, and wait for instantiation.
11944 // - There's a scope specifier that does match some template
11945 // parameter lists, which we don't handle right now.
11946 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011947 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011948 // C++ [class.friend]p6:
11949 // A function can be defined in a friend declaration of a class if and
11950 // only if the class is a non-local class (9.8), the function name is
11951 // unqualified, and the function has namespace scope.
11952 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11953 << SS.getScopeRep();
11954 }
11955
John McCallde3fd222010-10-12 23:13:28 +000011956 DC = CurContext;
11957 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011958 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011959
John McCallf7cfb222010-10-13 05:45:15 +000011960 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011961 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011962 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11963 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11964 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011965 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011966 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11967 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000011968 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011969 }
John McCall07e91c02009-08-06 02:15:43 +000011970 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011971
Douglas Gregordd847ba2011-11-03 16:37:14 +000011972 // FIXME: This is an egregious hack to cope with cases where the scope stack
11973 // does not contain the declaration context, i.e., in an out-of-line
11974 // definition of a class.
11975 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11976 if (!DCScope) {
11977 FakeDCScope.setEntity(DC);
11978 DCScope = &FakeDCScope;
11979 }
Richard Smith114394f2013-08-09 04:35:01 +000011980
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011981 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011982 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011983 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000011984 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000011985
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011986 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011987
Richard Smith114394f2013-08-09 04:35:01 +000011988 // If we performed typo correction, we might have added a scope specifier
11989 // and changed the decl context.
11990 DC = ND->getDeclContext();
11991
John McCall759e32b2009-08-31 22:39:49 +000011992 // Add the function declaration to the appropriate lookup tables,
11993 // adjusting the redeclarations list as necessary. We don't
11994 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011995 //
John McCall759e32b2009-08-31 22:39:49 +000011996 // Also update the scope-based lookup if the target context's
11997 // lookup context is in lexical scope.
11998 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011999 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012000 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012001 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012002 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012003 }
John McCallaa74a0c2009-08-28 07:59:38 +000012004
12005 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012006 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012007 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012008 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012009 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012010
John McCalla0a96892012-08-10 03:15:35 +000012011 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012012 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012013 } else {
12014 if (DC->isRecord()) CheckFriendAccess(ND);
12015
John McCall2c2eb122010-10-16 06:59:13 +000012016 FunctionDecl *FD;
12017 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12018 FD = FTD->getTemplatedDecl();
12019 else
12020 FD = cast<FunctionDecl>(ND);
12021
David Majnemer502b0ed2013-06-25 23:09:30 +000012022 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12023 // default argument expression, that declaration shall be a definition
12024 // and shall be the only declaration of the function or function
12025 // template in the translation unit.
12026 if (functionDeclHasDefaultArgument(FD)) {
12027 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12028 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12029 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12030 } else if (!D.isFunctionDefinition())
12031 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12032 }
12033
John McCall2c2eb122010-10-16 06:59:13 +000012034 // Mark templated-scope function declarations as unsupported.
12035 if (FD->getNumTemplateParameterLists())
12036 FrD->setUnsupportedFriend(true);
12037 }
John McCallde3fd222010-10-12 23:13:28 +000012038
John McCall48871652010-08-21 09:40:31 +000012039 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012040}
12041
John McCall48871652010-08-21 09:40:31 +000012042void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12043 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012044
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012045 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012046 if (!Fn) {
12047 Diag(DelLoc, diag::err_deleted_non_function);
12048 return;
12049 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012050
Douglas Gregorec9fd132012-01-14 16:38:05 +000012051 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012052 // Don't consider the implicit declaration we generate for explicit
12053 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012054 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12055 Prev->getPreviousDecl()) &&
12056 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012057 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012058 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12059 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12060 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012061 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012062 // If the declaration wasn't the first, we delete the function anyway for
12063 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012064 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012065 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012066
Nico Rieck9de0a572014-05-29 16:51:19 +000012067 // dllimport/dllexport cannot be deleted.
12068 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12069 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12070 Fn->setInvalidDecl();
12071 }
12072
Richard Smithb4d2a152013-04-02 19:38:47 +000012073 if (Fn->isDeleted())
12074 return;
12075
12076 // See if we're deleting a function which is already known to override a
12077 // non-deleted virtual function.
12078 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12079 bool IssuedDiagnostic = false;
12080 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12081 E = MD->end_overridden_methods();
12082 I != E; ++I) {
12083 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12084 if (!IssuedDiagnostic) {
12085 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12086 IssuedDiagnostic = true;
12087 }
12088 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12089 }
12090 }
12091 }
12092
Richard Smithb63b6ee2014-01-22 01:43:19 +000012093 // C++11 [basic.start.main]p3:
12094 // A program that defines main as deleted [...] is ill-formed.
12095 if (Fn->isMain())
12096 Diag(DelLoc, diag::err_deleted_main);
12097
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012098 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012099}
Sebastian Redl4c018662009-04-27 21:33:24 +000012100
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012101void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012102 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012103
12104 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012105 if (MD->getParent()->isDependentType()) {
12106 MD->setDefaulted();
12107 MD->setExplicitlyDefaulted();
12108 return;
12109 }
12110
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012111 CXXSpecialMember Member = getSpecialMember(MD);
12112 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012113 if (!MD->isInvalidDecl())
12114 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012115 return;
12116 }
12117
12118 MD->setDefaulted();
12119 MD->setExplicitlyDefaulted();
12120
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012121 // If this definition appears within the record, do the checking when
12122 // the record is complete.
12123 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012124 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012125 // Find the uninstantiated declaration that actually had the '= default'
12126 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012127 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012128
Richard Smith3901dfe2013-03-27 00:22:47 +000012129 // If the method was defaulted on its first declaration, we will have
12130 // already performed the checking in CheckCompletedCXXClass. Such a
12131 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012132 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012133 return;
12134
Richard Smithd3b5c9082012-07-27 04:22:15 +000012135 CheckExplicitlyDefaultedSpecialMember(MD);
12136
Richard Smithbd305122012-12-11 01:14:52 +000012137 // The exception specification is needed because we are defining the
12138 // function.
12139 ResolveExceptionSpec(DefaultLoc,
12140 MD->getType()->castAs<FunctionProtoType>());
12141
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012142 if (MD->isInvalidDecl())
12143 return;
12144
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012145 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012146 case CXXDefaultConstructor:
12147 DefineImplicitDefaultConstructor(DefaultLoc,
12148 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012149 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012150 case CXXCopyConstructor:
12151 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012152 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012153 case CXXCopyAssignment:
12154 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012155 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012156 case CXXDestructor:
12157 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012158 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012159 case CXXMoveConstructor:
12160 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012161 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012162 case CXXMoveAssignment:
12163 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012164 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012165 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012166 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012167 }
12168 } else {
12169 Diag(DefaultLoc, diag::err_default_special_members);
12170 }
12171}
12172
Sebastian Redl4c018662009-04-27 21:33:24 +000012173static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012174 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012175 Stmt *SubStmt = *CI;
12176 if (!SubStmt)
12177 continue;
12178 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012179 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012180 diag::err_return_in_constructor_handler);
12181 if (!isa<Expr>(SubStmt))
12182 SearchForReturnInStmt(Self, SubStmt);
12183 }
12184}
12185
12186void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12187 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12188 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12189 SearchForReturnInStmt(*this, Handler);
12190 }
12191}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012192
David Blaikie68f71a32013-01-18 23:03:15 +000012193bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012194 const CXXMethodDecl *Old) {
12195 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12196 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12197
12198 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12199
12200 // If the calling conventions match, everything is fine
12201 if (NewCC == OldCC)
12202 return false;
12203
Hans Wennborg2545efe2013-12-11 17:42:11 +000012204 // If the calling conventions mismatch because the new function is static,
12205 // suppress the calling convention mismatch error; the error about static
12206 // function override (err_static_overrides_virtual from
12207 // Sema::CheckFunctionDeclaration) is more clear.
12208 if (New->getStorageClass() == SC_Static)
12209 return false;
12210
Reid Kleckner78af0702013-08-27 23:08:25 +000012211 Diag(New->getLocation(),
12212 diag::err_conflicting_overriding_cc_attributes)
12213 << New->getDeclName() << New->getType() << Old->getType();
12214 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12215 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012216}
12217
Mike Stump11289f42009-09-09 15:08:12 +000012218bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012219 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012220 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12221 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012222
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012223 if (Context.hasSameType(NewTy, OldTy) ||
12224 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012225 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012226
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012227 // Check if the return types are covariant
12228 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012229
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012230 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012231 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12232 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012233 NewClassTy = NewPT->getPointeeType();
12234 OldClassTy = OldPT->getPointeeType();
12235 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012236 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12237 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12238 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12239 NewClassTy = NewRT->getPointeeType();
12240 OldClassTy = OldRT->getPointeeType();
12241 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012242 }
12243 }
Mike Stump11289f42009-09-09 15:08:12 +000012244
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012245 // The return types aren't either both pointers or references to a class type.
12246 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012247 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012248 diag::err_different_return_type_for_overriding_virtual_function)
12249 << New->getDeclName() << NewTy << OldTy;
12250 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012251
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012252 return true;
12253 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012254
Anders Carlssone60365b2009-12-31 18:34:24 +000012255 // C++ [class.virtual]p6:
12256 // If the return type of D::f differs from the return type of B::f, the
12257 // class type in the return type of D::f shall be complete at the point of
12258 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012259 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12260 if (!RT->isBeingDefined() &&
12261 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012262 diag::err_covariant_return_incomplete,
12263 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012264 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012265 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012266
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012267 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012268 // Check if the new class derives from the old class.
12269 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12270 Diag(New->getLocation(),
12271 diag::err_covariant_return_not_derived)
12272 << New->getDeclName() << NewTy << OldTy;
12273 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12274 return true;
12275 }
Mike Stump11289f42009-09-09 15:08:12 +000012276
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012277 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012278 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012279 diag::err_covariant_return_inaccessible_base,
12280 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12281 // FIXME: Should this point to the return type?
Craig Topperc3ec1492014-05-26 06:22:03 +000012282 New->getLocation(), SourceRange(), New->getDeclName(),
12283 nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012284 // FIXME: this note won't trigger for delayed access control
12285 // diagnostics, and it's impossible to get an undelayed error
12286 // here from access control during the original parse because
12287 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012288 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12289 return true;
12290 }
12291 }
Mike Stump11289f42009-09-09 15:08:12 +000012292
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012293 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012294 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012295 Diag(New->getLocation(),
12296 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012297 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012298 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12299 return true;
12300 };
Mike Stump11289f42009-09-09 15:08:12 +000012301
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012302
12303 // The new class type must have the same or less qualifiers as the old type.
12304 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12305 Diag(New->getLocation(),
12306 diag::err_covariant_return_type_class_type_more_qualified)
12307 << New->getDeclName() << NewTy << OldTy;
12308 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12309 return true;
12310 };
Mike Stump11289f42009-09-09 15:08:12 +000012311
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012312 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012313}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012314
Douglas Gregor21920e372009-12-01 17:24:26 +000012315/// \brief Mark the given method pure.
12316///
12317/// \param Method the method to be marked pure.
12318///
12319/// \param InitRange the source range that covers the "0" initializer.
12320bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012321 SourceLocation EndLoc = InitRange.getEnd();
12322 if (EndLoc.isValid())
12323 Method->setRangeEnd(EndLoc);
12324
Douglas Gregor21920e372009-12-01 17:24:26 +000012325 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12326 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012327 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012328 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012329
12330 if (!Method->isInvalidDecl())
12331 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12332 << Method->getDeclName() << InitRange;
12333 return true;
12334}
12335
Douglas Gregor926410d2012-02-21 02:22:07 +000012336/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012337static bool isStaticDataMember(const Decl *D) {
12338 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12339 return Var->isStaticDataMember();
12340
12341 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012342}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012343
John McCall1f4ee7b2009-12-19 09:28:58 +000012344/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12345/// an initializer for the out-of-line declaration 'Dcl'. The scope
12346/// is a fresh scope pushed for just this purpose.
12347///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012348/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12349/// static data member of class X, names should be looked up in the scope of
12350/// class X.
John McCall48871652010-08-21 09:40:31 +000012351void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012352 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012353 if (!D || D->isInvalidDecl())
12354 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012355
Richard Smitha2302242013-12-05 07:51:02 +000012356 // We will always have a nested name specifier here, but this declaration
12357 // might not be out of line if the specifier names the current namespace:
12358 // extern int n;
12359 // int ::n = 0;
12360 if (D->isOutOfLine())
12361 EnterDeclaratorContext(S, D->getDeclContext());
12362
Douglas Gregor926410d2012-02-21 02:22:07 +000012363 // If we are parsing the initializer for a static data member, push a
12364 // new expression evaluation context that is associated with this static
12365 // data member.
12366 if (isStaticDataMember(D))
12367 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012368}
12369
12370/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012371/// initializer for the out-of-line declaration 'D'.
12372void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012373 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012374 if (!D || D->isInvalidDecl())
12375 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012376
Douglas Gregor926410d2012-02-21 02:22:07 +000012377 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012378 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012379
Richard Smitha2302242013-12-05 07:51:02 +000012380 if (D->isOutOfLine())
12381 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012382}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012383
12384/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12385/// C++ if/switch/while/for statement.
12386/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012387DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012388 // C++ 6.4p2:
12389 // The declarator shall not specify a function or an array.
12390 // The type-specifier-seq shall not contain typedef and shall not declare a
12391 // new class or enumeration.
12392 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12393 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012394
12395 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012396 if (!Dcl)
12397 return true;
12398
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012399 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12400 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012401 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012402 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012403 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012404
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012405 return Dcl;
12406}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012407
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012408void Sema::LoadExternalVTableUses() {
12409 if (!ExternalSource)
12410 return;
12411
12412 SmallVector<ExternalVTableUse, 4> VTables;
12413 ExternalSource->ReadUsedVTables(VTables);
12414 SmallVector<VTableUse, 4> NewUses;
12415 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12416 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12417 = VTablesUsed.find(VTables[I].Record);
12418 // Even if a definition wasn't required before, it may be required now.
12419 if (Pos != VTablesUsed.end()) {
12420 if (!Pos->second && VTables[I].DefinitionRequired)
12421 Pos->second = true;
12422 continue;
12423 }
12424
12425 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12426 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12427 }
12428
12429 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12430}
12431
Douglas Gregor88d292c2010-05-13 16:44:06 +000012432void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12433 bool DefinitionRequired) {
12434 // Ignore any vtable uses in unevaluated operands or for classes that do
12435 // not have a vtable.
12436 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012437 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012438 return;
12439
Douglas Gregor88d292c2010-05-13 16:44:06 +000012440 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012441 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012442 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12443 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12444 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12445 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012446 // If we already had an entry, check to see if we are promoting this vtable
12447 // to required a definition. If so, we need to reappend to the VTableUses
12448 // list, since we may have already processed the first entry.
12449 if (DefinitionRequired && !Pos.first->second) {
12450 Pos.first->second = true;
12451 } else {
12452 // Otherwise, we can early exit.
12453 return;
12454 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012455 } else {
12456 // The Microsoft ABI requires that we perform the destructor body
12457 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12458 // the deleting destructor is emitted with the vtable, not with the
12459 // destructor definition as in the Itanium ABI.
12460 // If it has a definition, we do the check at that point instead.
12461 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12462 Class->hasUserDeclaredDestructor() &&
12463 !Class->getDestructor()->isDefined() &&
12464 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012465 CXXDestructorDecl *DD = Class->getDestructor();
12466 ContextRAII SavedContext(*this, DD);
12467 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012468 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012469 }
12470
12471 // Local classes need to have their virtual members marked
12472 // immediately. For all other classes, we mark their virtual members
12473 // at the end of the translation unit.
12474 if (Class->isLocalClass())
12475 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012476 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012477 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012478}
12479
Douglas Gregor88d292c2010-05-13 16:44:06 +000012480bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012481 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012482 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012483 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012484
Douglas Gregor88d292c2010-05-13 16:44:06 +000012485 // Note: The VTableUses vector could grow as a result of marking
12486 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012487 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012488 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012489 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012490 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012491 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012492 if (!Class)
12493 continue;
12494
12495 SourceLocation Loc = VTableUses[I].second;
12496
Richard Smithd3b5c9082012-07-27 04:22:15 +000012497 bool DefineVTable = true;
12498
Douglas Gregor88d292c2010-05-13 16:44:06 +000012499 // If this class has a key function, but that key function is
12500 // defined in another translation unit, we don't need to emit the
12501 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012502 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012503 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012504 // The key function is in another translation unit.
12505 DefineVTable = false;
12506 TemplateSpecializationKind TSK =
12507 KeyFunction->getTemplateSpecializationKind();
12508 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12509 TSK != TSK_ImplicitInstantiation &&
12510 "Instantiations don't have key functions");
12511 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012512 } else if (!KeyFunction) {
12513 // If we have a class with no key function that is the subject
12514 // of an explicit instantiation declaration, suppress the
12515 // vtable; it will live with the explicit instantiation
12516 // definition.
12517 bool IsExplicitInstantiationDeclaration
12518 = Class->getTemplateSpecializationKind()
12519 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012520 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012521 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012522 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012523 if (TSK == TSK_ExplicitInstantiationDeclaration)
12524 IsExplicitInstantiationDeclaration = true;
12525 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12526 IsExplicitInstantiationDeclaration = false;
12527 break;
12528 }
12529 }
12530
12531 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012532 DefineVTable = false;
12533 }
12534
12535 // The exception specifications for all virtual members may be needed even
12536 // if we are not providing an authoritative form of the vtable in this TU.
12537 // We may choose to emit it available_externally anyway.
12538 if (!DefineVTable) {
12539 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12540 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012541 }
12542
12543 // Mark all of the virtual members of this class as referenced, so
12544 // that we can build a vtable. Then, tell the AST consumer that a
12545 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012546 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012547 MarkVirtualMembersReferenced(Loc, Class);
12548 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12549 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12550
12551 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012552 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012553 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012554 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012555 if (!KeyFunction ||
12556 (KeyFunction->hasBody(KeyFunctionDef) &&
12557 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012558 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12559 TSK_ExplicitInstantiationDefinition
12560 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12561 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012562 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012563 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012564 VTableUses.clear();
12565
Douglas Gregor97509692011-04-22 22:25:37 +000012566 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012567}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012568
Richard Smithd3b5c9082012-07-27 04:22:15 +000012569void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12570 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012571 for (const auto *I : RD->methods())
12572 if (I->isVirtual() && !I->isPure())
12573 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012574}
12575
Rafael Espindola5b334082010-03-26 00:36:59 +000012576void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12577 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012578 // Mark all functions which will appear in RD's vtable as used.
12579 CXXFinalOverriderMap FinalOverriders;
12580 RD->getFinalOverriders(FinalOverriders);
12581 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12582 E = FinalOverriders.end();
12583 I != E; ++I) {
12584 for (OverridingMethods::const_iterator OI = I->second.begin(),
12585 OE = I->second.end();
12586 OI != OE; ++OI) {
12587 assert(OI->second.size() > 0 && "no final overrider");
12588 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012589
Richard Smith4ff9ff92012-07-07 06:59:51 +000012590 // C++ [basic.def.odr]p2:
12591 // [...] A virtual member function is used if it is not pure. [...]
12592 if (!Overrider->isPure())
12593 MarkFunctionReferenced(Loc, Overrider);
12594 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012595 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012596
12597 // Only classes that have virtual bases need a VTT.
12598 if (RD->getNumVBases() == 0)
12599 return;
12600
Aaron Ballman574705e2014-03-13 15:41:46 +000012601 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012602 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012603 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012604 if (Base->getNumVBases() == 0)
12605 continue;
12606 MarkVirtualMembersReferenced(Loc, Base);
12607 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012608}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012609
12610/// SetIvarInitializers - This routine builds initialization ASTs for the
12611/// Objective-C implementation whose ivars need be initialized.
12612void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012613 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012614 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012615 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012616 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012617 CollectIvarsToConstructOrDestruct(OID, ivars);
12618 if (ivars.empty())
12619 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012620 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012621 for (unsigned i = 0; i < ivars.size(); i++) {
12622 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012623 if (Field->isInvalidDecl())
12624 continue;
12625
Alexis Hunt1d792652011-01-08 20:30:50 +000012626 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012627 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12628 InitializationKind InitKind =
12629 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012630
12631 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12632 ExprResult MemberInit =
12633 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012634 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012635 // Note, MemberInit could actually come back empty if no initialization
12636 // is required (e.g., because it would call a trivial default constructor)
12637 if (!MemberInit.get() || MemberInit.isInvalid())
12638 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012639
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012640 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012641 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12642 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012643 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000012644 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012645 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012646
12647 // Be sure that the destructor is accessible and is marked as referenced.
12648 if (const RecordType *RecordTy
12649 = Context.getBaseElementType(Field->getType())
12650 ->getAs<RecordType>()) {
12651 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012652 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012653 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012654 CheckDestructorAccess(Field->getLocation(), Destructor,
12655 PDiag(diag::err_access_dtor_ivar)
12656 << Context.getBaseElementType(Field->getType()));
12657 }
12658 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012659 }
12660 ObjCImplementation->setIvarInitializers(Context,
12661 AllToInit.data(), AllToInit.size());
12662 }
12663}
Alexis Hunt6118d662011-05-04 05:57:24 +000012664
Alexis Hunt27a761d2011-05-04 23:29:54 +000012665static
12666void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12667 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12668 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12669 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12670 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012671 if (Ctor->isInvalidDecl())
12672 return;
12673
Richard Smith802c4b72012-08-23 06:16:52 +000012674 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12675
12676 // Target may not be determinable yet, for instance if this is a dependent
12677 // call in an uninstantiated template.
12678 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012679 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000012680 (void)Target->hasBody(FNTarget);
12681 Target = const_cast<CXXConstructorDecl*>(
12682 cast_or_null<CXXConstructorDecl>(FNTarget));
12683 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012684
12685 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12686 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000012687 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012688
12689 if (!Current.insert(Canonical))
12690 return;
12691
12692 // We know that beyond here, we aren't chaining into a cycle.
12693 if (!Target || !Target->isDelegatingConstructor() ||
12694 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012695 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012696 Current.clear();
12697 // We've hit a cycle.
12698 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12699 Current.count(TCanonical)) {
12700 // If we haven't diagnosed this cycle yet, do so now.
12701 if (!Invalid.count(TCanonical)) {
12702 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012703 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012704 << Ctor;
12705
Richard Smith802c4b72012-08-23 06:16:52 +000012706 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012707 if (TCanonical != Canonical)
12708 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12709
12710 CXXConstructorDecl *C = Target;
12711 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012712 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012713 (void)C->getTargetConstructor()->hasBody(FNTarget);
12714 assert(FNTarget && "Ctor cycle through bodiless function");
12715
Richard Smith802c4b72012-08-23 06:16:52 +000012716 C = const_cast<CXXConstructorDecl*>(
12717 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012718 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12719 }
12720 }
12721
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012722 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012723 Current.clear();
12724 } else {
12725 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12726 }
12727}
12728
12729
Alexis Hunt6118d662011-05-04 05:57:24 +000012730void Sema::CheckDelegatingCtorCycles() {
12731 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12732
Douglas Gregorbae31202011-07-27 21:57:17 +000012733 for (DelegatingCtorDeclsType::iterator
12734 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012735 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012736 I != E; ++I)
12737 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012738
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012739 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12740 CE = Invalid.end();
12741 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012742 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012743}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012744
Douglas Gregor3024f072012-04-16 07:05:22 +000012745namespace {
12746 /// \brief AST visitor that finds references to the 'this' expression.
12747 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12748 Sema &S;
12749
12750 public:
12751 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12752
12753 bool VisitCXXThisExpr(CXXThisExpr *E) {
12754 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12755 << E->isImplicit();
12756 return false;
12757 }
12758 };
12759}
12760
12761bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12762 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12763 if (!TSInfo)
12764 return false;
12765
12766 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012767 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012768 if (!ProtoTL)
12769 return false;
12770
12771 // C++11 [expr.prim.general]p3:
12772 // [The expression this] shall not appear before the optional
12773 // cv-qualifier-seq and it shall not appear within the declaration of a
12774 // static member function (although its type and value category are defined
12775 // within a static member function as they are within a non-static member
12776 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012777 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012778 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012779 FindCXXThisExpr Finder(*this);
12780
12781 // If the return type came after the cv-qualifier-seq, check it now.
12782 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012783 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012784 return true;
12785
12786 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012787 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12788 return true;
12789
12790 return checkThisInStaticMemberFunctionAttributes(Method);
12791}
12792
12793bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12794 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12795 if (!TSInfo)
12796 return false;
12797
12798 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012799 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012800 if (!ProtoTL)
12801 return false;
12802
David Blaikie6adc78e2013-02-18 22:06:02 +000012803 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012804 FindCXXThisExpr Finder(*this);
12805
Douglas Gregor3024f072012-04-16 07:05:22 +000012806 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012807 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012808 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012809 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012810 case EST_DynamicNone:
12811 case EST_MSAny:
12812 case EST_None:
12813 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012814
Douglas Gregor3024f072012-04-16 07:05:22 +000012815 case EST_ComputedNoexcept:
12816 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12817 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012818
Douglas Gregor3024f072012-04-16 07:05:22 +000012819 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012820 for (const auto &E : Proto->exceptions()) {
12821 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012822 return true;
12823 }
12824 break;
12825 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012826
12827 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012828}
12829
12830bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12831 FindCXXThisExpr Finder(*this);
12832
12833 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012834 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012835 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000012836 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000012837 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012838 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012839 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012840 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012841 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012842 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012843 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012844 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012845 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012846 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012847 Arg = ETLF->getSuccessValue();
12848 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012849 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012850 Arg = STLF->getSuccessValue();
12851 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012852 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012853 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012854 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012855 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012856 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012857 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012858 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012859 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012860 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12861 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12862 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012863 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012864
12865 if (Arg && !Finder.TraverseStmt(Arg))
12866 return true;
12867
12868 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12869 if (!Finder.TraverseStmt(Args[I]))
12870 return true;
12871 }
12872 }
12873
12874 return false;
12875}
12876
Douglas Gregor433e0532012-04-16 18:27:27 +000012877void
12878Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12879 ArrayRef<ParsedType> DynamicExceptions,
12880 ArrayRef<SourceRange> DynamicExceptionRanges,
12881 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012882 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012883 FunctionProtoType::ExtProtoInfo &EPI) {
12884 Exceptions.clear();
12885 EPI.ExceptionSpecType = EST;
12886 if (EST == EST_Dynamic) {
12887 Exceptions.reserve(DynamicExceptions.size());
12888 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12889 // FIXME: Preserve type source info.
12890 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12891
12892 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12893 collectUnexpandedParameterPacks(ET, Unexpanded);
12894 if (!Unexpanded.empty()) {
12895 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12896 UPPC_ExceptionType,
12897 Unexpanded);
12898 continue;
12899 }
12900
12901 // Check that the type is valid for an exception spec, and
12902 // drop it if not.
12903 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12904 Exceptions.push_back(ET);
12905 }
12906 EPI.NumExceptions = Exceptions.size();
12907 EPI.Exceptions = Exceptions.data();
12908 return;
12909 }
12910
12911 if (EST == EST_ComputedNoexcept) {
12912 // If an error occurred, there's no expression here.
12913 if (NoexceptExpr) {
12914 assert((NoexceptExpr->isTypeDependent() ||
12915 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12916 Context.BoolTy) &&
12917 "Parser should have made sure that the expression is boolean");
12918 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12919 EPI.ExceptionSpecType = EST_BasicNoexcept;
12920 return;
12921 }
12922
12923 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000012924 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000012925 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012926 /*AllowFold*/ false).get();
Douglas Gregor433e0532012-04-16 18:27:27 +000012927 EPI.NoexceptExpr = NoexceptExpr;
12928 }
12929 return;
12930 }
12931}
12932
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012933/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12934Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12935 // Implicitly declared functions (e.g. copy constructors) are
12936 // __host__ __device__
12937 if (D->isImplicit())
12938 return CFT_HostDevice;
12939
12940 if (D->hasAttr<CUDAGlobalAttr>())
12941 return CFT_Global;
12942
12943 if (D->hasAttr<CUDADeviceAttr>()) {
12944 if (D->hasAttr<CUDAHostAttr>())
12945 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012946 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012947 }
12948
12949 return CFT_Host;
12950}
12951
12952bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12953 CUDAFunctionTarget CalleeTarget) {
12954 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12955 // Callable from the device only."
12956 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12957 return true;
12958
12959 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12960 // Callable from the host only."
12961 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12962 // Callable from the host only."
12963 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12964 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12965 return true;
12966
12967 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12968 return true;
12969
12970 return false;
12971}
John McCall5e77d762013-04-16 07:28:30 +000012972
12973/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12974///
12975MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12976 SourceLocation DeclStart,
12977 Declarator &D, Expr *BitWidth,
12978 InClassInitStyle InitStyle,
12979 AccessSpecifier AS,
12980 AttributeList *MSPropertyAttr) {
12981 IdentifierInfo *II = D.getIdentifier();
12982 if (!II) {
12983 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000012984 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000012985 }
12986 SourceLocation Loc = D.getIdentifierLoc();
12987
12988 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12989 QualType T = TInfo->getType();
12990 if (getLangOpts().CPlusPlus) {
12991 CheckExtraCXXDefaultArguments(D);
12992
12993 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12994 UPPC_DataMemberType)) {
12995 D.setInvalidType();
12996 T = Context.IntTy;
12997 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12998 }
12999 }
13000
13001 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13002
13003 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13004 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13005 diag::err_invalid_thread)
13006 << DeclSpec::getSpecifierName(TSCS);
13007
13008 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013009 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013010 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13011 LookupName(Previous, S);
13012 switch (Previous.getResultKind()) {
13013 case LookupResult::Found:
13014 case LookupResult::FoundUnresolvedValue:
13015 PrevDecl = Previous.getAsSingle<NamedDecl>();
13016 break;
13017
13018 case LookupResult::FoundOverloaded:
13019 PrevDecl = Previous.getRepresentativeDecl();
13020 break;
13021
13022 case LookupResult::NotFound:
13023 case LookupResult::NotFoundInCurrentInstantiation:
13024 case LookupResult::Ambiguous:
13025 break;
13026 }
13027
13028 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13029 // Maybe we will complain about the shadowed template parameter.
13030 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13031 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013032 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013033 }
13034
13035 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013036 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013037
13038 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013039 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013040 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13041 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013042 ProcessDeclAttributes(TUScope, NewPD, D);
13043 NewPD->setAccess(AS);
13044
13045 if (NewPD->isInvalidDecl())
13046 Record->setInvalidDecl();
13047
13048 if (D.getDeclSpec().isModulePrivateSpecified())
13049 NewPD->setModulePrivate();
13050
13051 if (NewPD->isInvalidDecl() && PrevDecl) {
13052 // Don't introduce NewFD into scope; there's already something
13053 // with the same name in the same scope.
13054 } else if (II) {
13055 PushOnScopeChains(NewPD, S);
13056 } else
13057 Record->addDecl(NewPD);
13058
13059 return NewPD;
13060}