1*67e74705SXin Li //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements semantic analysis for C++ declarations.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
15*67e74705SXin Li #include "clang/AST/ASTConsumer.h"
16*67e74705SXin Li #include "clang/AST/ASTContext.h"
17*67e74705SXin Li #include "clang/AST/ASTLambda.h"
18*67e74705SXin Li #include "clang/AST/ASTMutationListener.h"
19*67e74705SXin Li #include "clang/AST/CXXInheritance.h"
20*67e74705SXin Li #include "clang/AST/CharUnits.h"
21*67e74705SXin Li #include "clang/AST/EvaluatedExprVisitor.h"
22*67e74705SXin Li #include "clang/AST/ExprCXX.h"
23*67e74705SXin Li #include "clang/AST/RecordLayout.h"
24*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
25*67e74705SXin Li #include "clang/AST/StmtVisitor.h"
26*67e74705SXin Li #include "clang/AST/TypeLoc.h"
27*67e74705SXin Li #include "clang/AST/TypeOrdering.h"
28*67e74705SXin Li #include "clang/Basic/PartialDiagnostic.h"
29*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
30*67e74705SXin Li #include "clang/Lex/LiteralSupport.h"
31*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
32*67e74705SXin Li #include "clang/Sema/CXXFieldCollector.h"
33*67e74705SXin Li #include "clang/Sema/DeclSpec.h"
34*67e74705SXin Li #include "clang/Sema/Initialization.h"
35*67e74705SXin Li #include "clang/Sema/Lookup.h"
36*67e74705SXin Li #include "clang/Sema/ParsedTemplate.h"
37*67e74705SXin Li #include "clang/Sema/Scope.h"
38*67e74705SXin Li #include "clang/Sema/ScopeInfo.h"
39*67e74705SXin Li #include "clang/Sema/Template.h"
40*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
41*67e74705SXin Li #include "llvm/ADT/SmallString.h"
42*67e74705SXin Li #include <map>
43*67e74705SXin Li #include <set>
44*67e74705SXin Li
45*67e74705SXin Li using namespace clang;
46*67e74705SXin Li
47*67e74705SXin Li //===----------------------------------------------------------------------===//
48*67e74705SXin Li // CheckDefaultArgumentVisitor
49*67e74705SXin Li //===----------------------------------------------------------------------===//
50*67e74705SXin Li
51*67e74705SXin Li namespace {
52*67e74705SXin Li /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53*67e74705SXin Li /// the default argument of a parameter to determine whether it
54*67e74705SXin Li /// contains any ill-formed subexpressions. For example, this will
55*67e74705SXin Li /// diagnose the use of local variables or parameters within the
56*67e74705SXin Li /// default argument expression.
57*67e74705SXin Li class CheckDefaultArgumentVisitor
58*67e74705SXin Li : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59*67e74705SXin Li Expr *DefaultArg;
60*67e74705SXin Li Sema *S;
61*67e74705SXin Li
62*67e74705SXin Li public:
CheckDefaultArgumentVisitor(Expr * defarg,Sema * s)63*67e74705SXin Li CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64*67e74705SXin Li : DefaultArg(defarg), S(s) {}
65*67e74705SXin Li
66*67e74705SXin Li bool VisitExpr(Expr *Node);
67*67e74705SXin Li bool VisitDeclRefExpr(DeclRefExpr *DRE);
68*67e74705SXin Li bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69*67e74705SXin Li bool VisitLambdaExpr(LambdaExpr *Lambda);
70*67e74705SXin Li bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71*67e74705SXin Li };
72*67e74705SXin Li
73*67e74705SXin Li /// VisitExpr - Visit all of the children of this expression.
VisitExpr(Expr * Node)74*67e74705SXin Li bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75*67e74705SXin Li bool IsInvalid = false;
76*67e74705SXin Li for (Stmt *SubStmt : Node->children())
77*67e74705SXin Li IsInvalid |= Visit(SubStmt);
78*67e74705SXin Li return IsInvalid;
79*67e74705SXin Li }
80*67e74705SXin Li
81*67e74705SXin Li /// VisitDeclRefExpr - Visit a reference to a declaration, to
82*67e74705SXin Li /// determine whether this declaration can be used in the default
83*67e74705SXin Li /// argument expression.
VisitDeclRefExpr(DeclRefExpr * DRE)84*67e74705SXin Li bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85*67e74705SXin Li NamedDecl *Decl = DRE->getDecl();
86*67e74705SXin Li if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87*67e74705SXin Li // C++ [dcl.fct.default]p9
88*67e74705SXin Li // Default arguments are evaluated each time the function is
89*67e74705SXin Li // called. The order of evaluation of function arguments is
90*67e74705SXin Li // unspecified. Consequently, parameters of a function shall not
91*67e74705SXin Li // be used in default argument expressions, even if they are not
92*67e74705SXin Li // evaluated. Parameters of a function declared before a default
93*67e74705SXin Li // argument expression are in scope and can hide namespace and
94*67e74705SXin Li // class member names.
95*67e74705SXin Li return S->Diag(DRE->getLocStart(),
96*67e74705SXin Li diag::err_param_default_argument_references_param)
97*67e74705SXin Li << Param->getDeclName() << DefaultArg->getSourceRange();
98*67e74705SXin Li } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99*67e74705SXin Li // C++ [dcl.fct.default]p7
100*67e74705SXin Li // Local variables shall not be used in default argument
101*67e74705SXin Li // expressions.
102*67e74705SXin Li if (VDecl->isLocalVarDecl())
103*67e74705SXin Li return S->Diag(DRE->getLocStart(),
104*67e74705SXin Li diag::err_param_default_argument_references_local)
105*67e74705SXin Li << VDecl->getDeclName() << DefaultArg->getSourceRange();
106*67e74705SXin Li }
107*67e74705SXin Li
108*67e74705SXin Li return false;
109*67e74705SXin Li }
110*67e74705SXin Li
111*67e74705SXin Li /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(CXXThisExpr * ThisE)112*67e74705SXin Li bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113*67e74705SXin Li // C++ [dcl.fct.default]p8:
114*67e74705SXin Li // The keyword this shall not be used in a default argument of a
115*67e74705SXin Li // member function.
116*67e74705SXin Li return S->Diag(ThisE->getLocStart(),
117*67e74705SXin Li diag::err_param_default_argument_references_this)
118*67e74705SXin Li << ThisE->getSourceRange();
119*67e74705SXin Li }
120*67e74705SXin Li
VisitPseudoObjectExpr(PseudoObjectExpr * POE)121*67e74705SXin Li bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122*67e74705SXin Li bool Invalid = false;
123*67e74705SXin Li for (PseudoObjectExpr::semantics_iterator
124*67e74705SXin Li i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125*67e74705SXin Li Expr *E = *i;
126*67e74705SXin Li
127*67e74705SXin Li // Look through bindings.
128*67e74705SXin Li if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129*67e74705SXin Li E = OVE->getSourceExpr();
130*67e74705SXin Li assert(E && "pseudo-object binding without source expression?");
131*67e74705SXin Li }
132*67e74705SXin Li
133*67e74705SXin Li Invalid |= Visit(E);
134*67e74705SXin Li }
135*67e74705SXin Li return Invalid;
136*67e74705SXin Li }
137*67e74705SXin Li
VisitLambdaExpr(LambdaExpr * Lambda)138*67e74705SXin Li bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139*67e74705SXin Li // C++11 [expr.lambda.prim]p13:
140*67e74705SXin Li // A lambda-expression appearing in a default argument shall not
141*67e74705SXin Li // implicitly or explicitly capture any entity.
142*67e74705SXin Li if (Lambda->capture_begin() == Lambda->capture_end())
143*67e74705SXin Li return false;
144*67e74705SXin Li
145*67e74705SXin Li return S->Diag(Lambda->getLocStart(),
146*67e74705SXin Li diag::err_lambda_capture_default_arg);
147*67e74705SXin Li }
148*67e74705SXin Li }
149*67e74705SXin Li
150*67e74705SXin Li void
CalledDecl(SourceLocation CallLoc,const CXXMethodDecl * Method)151*67e74705SXin Li Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152*67e74705SXin Li const CXXMethodDecl *Method) {
153*67e74705SXin Li // If we have an MSAny spec already, don't bother.
154*67e74705SXin Li if (!Method || ComputedEST == EST_MSAny)
155*67e74705SXin Li return;
156*67e74705SXin Li
157*67e74705SXin Li const FunctionProtoType *Proto
158*67e74705SXin Li = Method->getType()->getAs<FunctionProtoType>();
159*67e74705SXin Li Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160*67e74705SXin Li if (!Proto)
161*67e74705SXin Li return;
162*67e74705SXin Li
163*67e74705SXin Li ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164*67e74705SXin Li
165*67e74705SXin Li // If we have a throw-all spec at this point, ignore the function.
166*67e74705SXin Li if (ComputedEST == EST_None)
167*67e74705SXin Li return;
168*67e74705SXin Li
169*67e74705SXin Li switch(EST) {
170*67e74705SXin Li // If this function can throw any exceptions, make a note of that.
171*67e74705SXin Li case EST_MSAny:
172*67e74705SXin Li case EST_None:
173*67e74705SXin Li ClearExceptions();
174*67e74705SXin Li ComputedEST = EST;
175*67e74705SXin Li return;
176*67e74705SXin Li // FIXME: If the call to this decl is using any of its default arguments, we
177*67e74705SXin Li // need to search them for potentially-throwing calls.
178*67e74705SXin Li // If this function has a basic noexcept, it doesn't affect the outcome.
179*67e74705SXin Li case EST_BasicNoexcept:
180*67e74705SXin Li return;
181*67e74705SXin Li // If we're still at noexcept(true) and there's a nothrow() callee,
182*67e74705SXin Li // change to that specification.
183*67e74705SXin Li case EST_DynamicNone:
184*67e74705SXin Li if (ComputedEST == EST_BasicNoexcept)
185*67e74705SXin Li ComputedEST = EST_DynamicNone;
186*67e74705SXin Li return;
187*67e74705SXin Li // Check out noexcept specs.
188*67e74705SXin Li case EST_ComputedNoexcept:
189*67e74705SXin Li {
190*67e74705SXin Li FunctionProtoType::NoexceptResult NR =
191*67e74705SXin Li Proto->getNoexceptSpec(Self->Context);
192*67e74705SXin Li assert(NR != FunctionProtoType::NR_NoNoexcept &&
193*67e74705SXin Li "Must have noexcept result for EST_ComputedNoexcept.");
194*67e74705SXin Li assert(NR != FunctionProtoType::NR_Dependent &&
195*67e74705SXin Li "Should not generate implicit declarations for dependent cases, "
196*67e74705SXin Li "and don't know how to handle them anyway.");
197*67e74705SXin Li // noexcept(false) -> no spec on the new function
198*67e74705SXin Li if (NR == FunctionProtoType::NR_Throw) {
199*67e74705SXin Li ClearExceptions();
200*67e74705SXin Li ComputedEST = EST_None;
201*67e74705SXin Li }
202*67e74705SXin Li // noexcept(true) won't change anything either.
203*67e74705SXin Li return;
204*67e74705SXin Li }
205*67e74705SXin Li default:
206*67e74705SXin Li break;
207*67e74705SXin Li }
208*67e74705SXin Li assert(EST == EST_Dynamic && "EST case not considered earlier.");
209*67e74705SXin Li assert(ComputedEST != EST_None &&
210*67e74705SXin Li "Shouldn't collect exceptions when throw-all is guaranteed.");
211*67e74705SXin Li ComputedEST = EST_Dynamic;
212*67e74705SXin Li // Record the exceptions in this function's exception specification.
213*67e74705SXin Li for (const auto &E : Proto->exceptions())
214*67e74705SXin Li if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215*67e74705SXin Li Exceptions.push_back(E);
216*67e74705SXin Li }
217*67e74705SXin Li
CalledExpr(Expr * E)218*67e74705SXin Li void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219*67e74705SXin Li if (!E || ComputedEST == EST_MSAny)
220*67e74705SXin Li return;
221*67e74705SXin Li
222*67e74705SXin Li // FIXME:
223*67e74705SXin Li //
224*67e74705SXin Li // C++0x [except.spec]p14:
225*67e74705SXin Li // [An] implicit exception-specification specifies the type-id T if and
226*67e74705SXin Li // only if T is allowed by the exception-specification of a function directly
227*67e74705SXin Li // invoked by f's implicit definition; f shall allow all exceptions if any
228*67e74705SXin Li // function it directly invokes allows all exceptions, and f shall allow no
229*67e74705SXin Li // exceptions if every function it directly invokes allows no exceptions.
230*67e74705SXin Li //
231*67e74705SXin Li // Note in particular that if an implicit exception-specification is generated
232*67e74705SXin Li // for a function containing a throw-expression, that specification can still
233*67e74705SXin Li // be noexcept(true).
234*67e74705SXin Li //
235*67e74705SXin Li // Note also that 'directly invoked' is not defined in the standard, and there
236*67e74705SXin Li // is no indication that we should only consider potentially-evaluated calls.
237*67e74705SXin Li //
238*67e74705SXin Li // Ultimately we should implement the intent of the standard: the exception
239*67e74705SXin Li // specification should be the set of exceptions which can be thrown by the
240*67e74705SXin Li // implicit definition. For now, we assume that any non-nothrow expression can
241*67e74705SXin Li // throw any exception.
242*67e74705SXin Li
243*67e74705SXin Li if (Self->canThrow(E))
244*67e74705SXin Li ComputedEST = EST_None;
245*67e74705SXin Li }
246*67e74705SXin Li
247*67e74705SXin Li bool
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)248*67e74705SXin Li Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249*67e74705SXin Li SourceLocation EqualLoc) {
250*67e74705SXin Li if (RequireCompleteType(Param->getLocation(), Param->getType(),
251*67e74705SXin Li diag::err_typecheck_decl_incomplete_type)) {
252*67e74705SXin Li Param->setInvalidDecl();
253*67e74705SXin Li return true;
254*67e74705SXin Li }
255*67e74705SXin Li
256*67e74705SXin Li // C++ [dcl.fct.default]p5
257*67e74705SXin Li // A default argument expression is implicitly converted (clause
258*67e74705SXin Li // 4) to the parameter type. The default argument expression has
259*67e74705SXin Li // the same semantic constraints as the initializer expression in
260*67e74705SXin Li // a declaration of a variable of the parameter type, using the
261*67e74705SXin Li // copy-initialization semantics (8.5).
262*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263*67e74705SXin Li Param);
264*67e74705SXin Li InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265*67e74705SXin Li EqualLoc);
266*67e74705SXin Li InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267*67e74705SXin Li ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268*67e74705SXin Li if (Result.isInvalid())
269*67e74705SXin Li return true;
270*67e74705SXin Li Arg = Result.getAs<Expr>();
271*67e74705SXin Li
272*67e74705SXin Li CheckCompletedExpr(Arg, EqualLoc);
273*67e74705SXin Li Arg = MaybeCreateExprWithCleanups(Arg);
274*67e74705SXin Li
275*67e74705SXin Li // Okay: add the default argument to the parameter
276*67e74705SXin Li Param->setDefaultArg(Arg);
277*67e74705SXin Li
278*67e74705SXin Li // We have already instantiated this parameter; provide each of the
279*67e74705SXin Li // instantiations with the uninstantiated default argument.
280*67e74705SXin Li UnparsedDefaultArgInstantiationsMap::iterator InstPos
281*67e74705SXin Li = UnparsedDefaultArgInstantiations.find(Param);
282*67e74705SXin Li if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283*67e74705SXin Li for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284*67e74705SXin Li InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285*67e74705SXin Li
286*67e74705SXin Li // We're done tracking this parameter's instantiations.
287*67e74705SXin Li UnparsedDefaultArgInstantiations.erase(InstPos);
288*67e74705SXin Li }
289*67e74705SXin Li
290*67e74705SXin Li return false;
291*67e74705SXin Li }
292*67e74705SXin Li
293*67e74705SXin Li /// ActOnParamDefaultArgument - Check whether the default argument
294*67e74705SXin Li /// provided for a function parameter is well-formed. If so, attach it
295*67e74705SXin Li /// to the parameter declaration.
296*67e74705SXin Li void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)297*67e74705SXin Li Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298*67e74705SXin Li Expr *DefaultArg) {
299*67e74705SXin Li if (!param || !DefaultArg)
300*67e74705SXin Li return;
301*67e74705SXin Li
302*67e74705SXin Li ParmVarDecl *Param = cast<ParmVarDecl>(param);
303*67e74705SXin Li UnparsedDefaultArgLocs.erase(Param);
304*67e74705SXin Li
305*67e74705SXin Li // Default arguments are only permitted in C++
306*67e74705SXin Li if (!getLangOpts().CPlusPlus) {
307*67e74705SXin Li Diag(EqualLoc, diag::err_param_default_argument)
308*67e74705SXin Li << DefaultArg->getSourceRange();
309*67e74705SXin Li Param->setInvalidDecl();
310*67e74705SXin Li return;
311*67e74705SXin Li }
312*67e74705SXin Li
313*67e74705SXin Li // Check for unexpanded parameter packs.
314*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315*67e74705SXin Li Param->setInvalidDecl();
316*67e74705SXin Li return;
317*67e74705SXin Li }
318*67e74705SXin Li
319*67e74705SXin Li // C++11 [dcl.fct.default]p3
320*67e74705SXin Li // A default argument expression [...] shall not be specified for a
321*67e74705SXin Li // parameter pack.
322*67e74705SXin Li if (Param->isParameterPack()) {
323*67e74705SXin Li Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324*67e74705SXin Li << DefaultArg->getSourceRange();
325*67e74705SXin Li return;
326*67e74705SXin Li }
327*67e74705SXin Li
328*67e74705SXin Li // Check that the default argument is well-formed
329*67e74705SXin Li CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330*67e74705SXin Li if (DefaultArgChecker.Visit(DefaultArg)) {
331*67e74705SXin Li Param->setInvalidDecl();
332*67e74705SXin Li return;
333*67e74705SXin Li }
334*67e74705SXin Li
335*67e74705SXin Li SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336*67e74705SXin Li }
337*67e74705SXin Li
338*67e74705SXin Li /// ActOnParamUnparsedDefaultArgument - We've seen a default
339*67e74705SXin Li /// argument for a function parameter, but we can't parse it yet
340*67e74705SXin Li /// because we're inside a class definition. Note that this default
341*67e74705SXin Li /// argument will be parsed later.
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)342*67e74705SXin Li void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343*67e74705SXin Li SourceLocation EqualLoc,
344*67e74705SXin Li SourceLocation ArgLoc) {
345*67e74705SXin Li if (!param)
346*67e74705SXin Li return;
347*67e74705SXin Li
348*67e74705SXin Li ParmVarDecl *Param = cast<ParmVarDecl>(param);
349*67e74705SXin Li Param->setUnparsedDefaultArg();
350*67e74705SXin Li UnparsedDefaultArgLocs[Param] = ArgLoc;
351*67e74705SXin Li }
352*67e74705SXin Li
353*67e74705SXin Li /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354*67e74705SXin Li /// the default argument for the parameter param failed.
ActOnParamDefaultArgumentError(Decl * param,SourceLocation EqualLoc)355*67e74705SXin Li void Sema::ActOnParamDefaultArgumentError(Decl *param,
356*67e74705SXin Li SourceLocation EqualLoc) {
357*67e74705SXin Li if (!param)
358*67e74705SXin Li return;
359*67e74705SXin Li
360*67e74705SXin Li ParmVarDecl *Param = cast<ParmVarDecl>(param);
361*67e74705SXin Li Param->setInvalidDecl();
362*67e74705SXin Li UnparsedDefaultArgLocs.erase(Param);
363*67e74705SXin Li Param->setDefaultArg(new(Context)
364*67e74705SXin Li OpaqueValueExpr(EqualLoc,
365*67e74705SXin Li Param->getType().getNonReferenceType(),
366*67e74705SXin Li VK_RValue));
367*67e74705SXin Li }
368*67e74705SXin Li
369*67e74705SXin Li /// CheckExtraCXXDefaultArguments - Check for any extra default
370*67e74705SXin Li /// arguments in the declarator, which is not a function declaration
371*67e74705SXin Li /// or definition and therefore is not permitted to have default
372*67e74705SXin Li /// arguments. This routine should be invoked for every declarator
373*67e74705SXin Li /// that is not a function declaration or definition.
CheckExtraCXXDefaultArguments(Declarator & D)374*67e74705SXin Li void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375*67e74705SXin Li // C++ [dcl.fct.default]p3
376*67e74705SXin Li // A default argument expression shall be specified only in the
377*67e74705SXin Li // parameter-declaration-clause of a function declaration or in a
378*67e74705SXin Li // template-parameter (14.1). It shall not be specified for a
379*67e74705SXin Li // parameter pack. If it is specified in a
380*67e74705SXin Li // parameter-declaration-clause, it shall not occur within a
381*67e74705SXin Li // declarator or abstract-declarator of a parameter-declaration.
382*67e74705SXin Li bool MightBeFunction = D.isFunctionDeclarationContext();
383*67e74705SXin Li for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384*67e74705SXin Li DeclaratorChunk &chunk = D.getTypeObject(i);
385*67e74705SXin Li if (chunk.Kind == DeclaratorChunk::Function) {
386*67e74705SXin Li if (MightBeFunction) {
387*67e74705SXin Li // This is a function declaration. It can have default arguments, but
388*67e74705SXin Li // keep looking in case its return type is a function type with default
389*67e74705SXin Li // arguments.
390*67e74705SXin Li MightBeFunction = false;
391*67e74705SXin Li continue;
392*67e74705SXin Li }
393*67e74705SXin Li for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394*67e74705SXin Li ++argIdx) {
395*67e74705SXin Li ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396*67e74705SXin Li if (Param->hasUnparsedDefaultArg()) {
397*67e74705SXin Li CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
398*67e74705SXin Li SourceRange SR;
399*67e74705SXin Li if (Toks->size() > 1)
400*67e74705SXin Li SR = SourceRange((*Toks)[1].getLocation(),
401*67e74705SXin Li Toks->back().getLocation());
402*67e74705SXin Li else
403*67e74705SXin Li SR = UnparsedDefaultArgLocs[Param];
404*67e74705SXin Li Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
405*67e74705SXin Li << SR;
406*67e74705SXin Li delete Toks;
407*67e74705SXin Li chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
408*67e74705SXin Li } else if (Param->getDefaultArg()) {
409*67e74705SXin Li Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410*67e74705SXin Li << Param->getDefaultArg()->getSourceRange();
411*67e74705SXin Li Param->setDefaultArg(nullptr);
412*67e74705SXin Li }
413*67e74705SXin Li }
414*67e74705SXin Li } else if (chunk.Kind != DeclaratorChunk::Paren) {
415*67e74705SXin Li MightBeFunction = false;
416*67e74705SXin Li }
417*67e74705SXin Li }
418*67e74705SXin Li }
419*67e74705SXin Li
functionDeclHasDefaultArgument(const FunctionDecl * FD)420*67e74705SXin Li static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421*67e74705SXin Li for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422*67e74705SXin Li const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423*67e74705SXin Li if (!PVD->hasDefaultArg())
424*67e74705SXin Li return false;
425*67e74705SXin Li if (!PVD->hasInheritedDefaultArg())
426*67e74705SXin Li return true;
427*67e74705SXin Li }
428*67e74705SXin Li return false;
429*67e74705SXin Li }
430*67e74705SXin Li
431*67e74705SXin Li /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432*67e74705SXin Li /// function, once we already know that they have the same
433*67e74705SXin Li /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434*67e74705SXin Li /// error, false otherwise.
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old,Scope * S)435*67e74705SXin Li bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436*67e74705SXin Li Scope *S) {
437*67e74705SXin Li bool Invalid = false;
438*67e74705SXin Li
439*67e74705SXin Li // The declaration context corresponding to the scope is the semantic
440*67e74705SXin Li // parent, unless this is a local function declaration, in which case
441*67e74705SXin Li // it is that surrounding function.
442*67e74705SXin Li DeclContext *ScopeDC = New->isLocalExternDecl()
443*67e74705SXin Li ? New->getLexicalDeclContext()
444*67e74705SXin Li : New->getDeclContext();
445*67e74705SXin Li
446*67e74705SXin Li // Find the previous declaration for the purpose of default arguments.
447*67e74705SXin Li FunctionDecl *PrevForDefaultArgs = Old;
448*67e74705SXin Li for (/**/; PrevForDefaultArgs;
449*67e74705SXin Li // Don't bother looking back past the latest decl if this is a local
450*67e74705SXin Li // extern declaration; nothing else could work.
451*67e74705SXin Li PrevForDefaultArgs = New->isLocalExternDecl()
452*67e74705SXin Li ? nullptr
453*67e74705SXin Li : PrevForDefaultArgs->getPreviousDecl()) {
454*67e74705SXin Li // Ignore hidden declarations.
455*67e74705SXin Li if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456*67e74705SXin Li continue;
457*67e74705SXin Li
458*67e74705SXin Li if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459*67e74705SXin Li !New->isCXXClassMember()) {
460*67e74705SXin Li // Ignore default arguments of old decl if they are not in
461*67e74705SXin Li // the same scope and this is not an out-of-line definition of
462*67e74705SXin Li // a member function.
463*67e74705SXin Li continue;
464*67e74705SXin Li }
465*67e74705SXin Li
466*67e74705SXin Li if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467*67e74705SXin Li // If only one of these is a local function declaration, then they are
468*67e74705SXin Li // declared in different scopes, even though isDeclInScope may think
469*67e74705SXin Li // they're in the same scope. (If both are local, the scope check is
470*67e74705SXin Li // sufficent, and if neither is local, then they are in the same scope.)
471*67e74705SXin Li continue;
472*67e74705SXin Li }
473*67e74705SXin Li
474*67e74705SXin Li // We found the right previous declaration.
475*67e74705SXin Li break;
476*67e74705SXin Li }
477*67e74705SXin Li
478*67e74705SXin Li // C++ [dcl.fct.default]p4:
479*67e74705SXin Li // For non-template functions, default arguments can be added in
480*67e74705SXin Li // later declarations of a function in the same
481*67e74705SXin Li // scope. Declarations in different scopes have completely
482*67e74705SXin Li // distinct sets of default arguments. That is, declarations in
483*67e74705SXin Li // inner scopes do not acquire default arguments from
484*67e74705SXin Li // declarations in outer scopes, and vice versa. In a given
485*67e74705SXin Li // function declaration, all parameters subsequent to a
486*67e74705SXin Li // parameter with a default argument shall have default
487*67e74705SXin Li // arguments supplied in this or previous declarations. A
488*67e74705SXin Li // default argument shall not be redefined by a later
489*67e74705SXin Li // declaration (not even to the same value).
490*67e74705SXin Li //
491*67e74705SXin Li // C++ [dcl.fct.default]p6:
492*67e74705SXin Li // Except for member functions of class templates, the default arguments
493*67e74705SXin Li // in a member function definition that appears outside of the class
494*67e74705SXin Li // definition are added to the set of default arguments provided by the
495*67e74705SXin Li // member function declaration in the class definition.
496*67e74705SXin Li for (unsigned p = 0, NumParams = PrevForDefaultArgs
497*67e74705SXin Li ? PrevForDefaultArgs->getNumParams()
498*67e74705SXin Li : 0;
499*67e74705SXin Li p < NumParams; ++p) {
500*67e74705SXin Li ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501*67e74705SXin Li ParmVarDecl *NewParam = New->getParamDecl(p);
502*67e74705SXin Li
503*67e74705SXin Li bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504*67e74705SXin Li bool NewParamHasDfl = NewParam->hasDefaultArg();
505*67e74705SXin Li
506*67e74705SXin Li if (OldParamHasDfl && NewParamHasDfl) {
507*67e74705SXin Li unsigned DiagDefaultParamID =
508*67e74705SXin Li diag::err_param_default_argument_redefinition;
509*67e74705SXin Li
510*67e74705SXin Li // MSVC accepts that default parameters be redefined for member functions
511*67e74705SXin Li // of template class. The new default parameter's value is ignored.
512*67e74705SXin Li Invalid = true;
513*67e74705SXin Li if (getLangOpts().MicrosoftExt) {
514*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515*67e74705SXin Li if (MD && MD->getParent()->getDescribedClassTemplate()) {
516*67e74705SXin Li // Merge the old default argument into the new parameter.
517*67e74705SXin Li NewParam->setHasInheritedDefaultArg();
518*67e74705SXin Li if (OldParam->hasUninstantiatedDefaultArg())
519*67e74705SXin Li NewParam->setUninstantiatedDefaultArg(
520*67e74705SXin Li OldParam->getUninstantiatedDefaultArg());
521*67e74705SXin Li else
522*67e74705SXin Li NewParam->setDefaultArg(OldParam->getInit());
523*67e74705SXin Li DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524*67e74705SXin Li Invalid = false;
525*67e74705SXin Li }
526*67e74705SXin Li }
527*67e74705SXin Li
528*67e74705SXin Li // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529*67e74705SXin Li // hint here. Alternatively, we could walk the type-source information
530*67e74705SXin Li // for NewParam to find the last source location in the type... but it
531*67e74705SXin Li // isn't worth the effort right now. This is the kind of test case that
532*67e74705SXin Li // is hard to get right:
533*67e74705SXin Li // int f(int);
534*67e74705SXin Li // void g(int (*fp)(int) = f);
535*67e74705SXin Li // void g(int (*fp)(int) = &f);
536*67e74705SXin Li Diag(NewParam->getLocation(), DiagDefaultParamID)
537*67e74705SXin Li << NewParam->getDefaultArgRange();
538*67e74705SXin Li
539*67e74705SXin Li // Look for the function declaration where the default argument was
540*67e74705SXin Li // actually written, which may be a declaration prior to Old.
541*67e74705SXin Li for (auto Older = PrevForDefaultArgs;
542*67e74705SXin Li OldParam->hasInheritedDefaultArg(); /**/) {
543*67e74705SXin Li Older = Older->getPreviousDecl();
544*67e74705SXin Li OldParam = Older->getParamDecl(p);
545*67e74705SXin Li }
546*67e74705SXin Li
547*67e74705SXin Li Diag(OldParam->getLocation(), diag::note_previous_definition)
548*67e74705SXin Li << OldParam->getDefaultArgRange();
549*67e74705SXin Li } else if (OldParamHasDfl) {
550*67e74705SXin Li // Merge the old default argument into the new parameter.
551*67e74705SXin Li // It's important to use getInit() here; getDefaultArg()
552*67e74705SXin Li // strips off any top-level ExprWithCleanups.
553*67e74705SXin Li NewParam->setHasInheritedDefaultArg();
554*67e74705SXin Li if (OldParam->hasUnparsedDefaultArg())
555*67e74705SXin Li NewParam->setUnparsedDefaultArg();
556*67e74705SXin Li else if (OldParam->hasUninstantiatedDefaultArg())
557*67e74705SXin Li NewParam->setUninstantiatedDefaultArg(
558*67e74705SXin Li OldParam->getUninstantiatedDefaultArg());
559*67e74705SXin Li else
560*67e74705SXin Li NewParam->setDefaultArg(OldParam->getInit());
561*67e74705SXin Li } else if (NewParamHasDfl) {
562*67e74705SXin Li if (New->getDescribedFunctionTemplate()) {
563*67e74705SXin Li // Paragraph 4, quoted above, only applies to non-template functions.
564*67e74705SXin Li Diag(NewParam->getLocation(),
565*67e74705SXin Li diag::err_param_default_argument_template_redecl)
566*67e74705SXin Li << NewParam->getDefaultArgRange();
567*67e74705SXin Li Diag(PrevForDefaultArgs->getLocation(),
568*67e74705SXin Li diag::note_template_prev_declaration)
569*67e74705SXin Li << false;
570*67e74705SXin Li } else if (New->getTemplateSpecializationKind()
571*67e74705SXin Li != TSK_ImplicitInstantiation &&
572*67e74705SXin Li New->getTemplateSpecializationKind() != TSK_Undeclared) {
573*67e74705SXin Li // C++ [temp.expr.spec]p21:
574*67e74705SXin Li // Default function arguments shall not be specified in a declaration
575*67e74705SXin Li // or a definition for one of the following explicit specializations:
576*67e74705SXin Li // - the explicit specialization of a function template;
577*67e74705SXin Li // - the explicit specialization of a member function template;
578*67e74705SXin Li // - the explicit specialization of a member function of a class
579*67e74705SXin Li // template where the class template specialization to which the
580*67e74705SXin Li // member function specialization belongs is implicitly
581*67e74705SXin Li // instantiated.
582*67e74705SXin Li Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583*67e74705SXin Li << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584*67e74705SXin Li << New->getDeclName()
585*67e74705SXin Li << NewParam->getDefaultArgRange();
586*67e74705SXin Li } else if (New->getDeclContext()->isDependentContext()) {
587*67e74705SXin Li // C++ [dcl.fct.default]p6 (DR217):
588*67e74705SXin Li // Default arguments for a member function of a class template shall
589*67e74705SXin Li // be specified on the initial declaration of the member function
590*67e74705SXin Li // within the class template.
591*67e74705SXin Li //
592*67e74705SXin Li // Reading the tea leaves a bit in DR217 and its reference to DR205
593*67e74705SXin Li // leads me to the conclusion that one cannot add default function
594*67e74705SXin Li // arguments for an out-of-line definition of a member function of a
595*67e74705SXin Li // dependent type.
596*67e74705SXin Li int WhichKind = 2;
597*67e74705SXin Li if (CXXRecordDecl *Record
598*67e74705SXin Li = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599*67e74705SXin Li if (Record->getDescribedClassTemplate())
600*67e74705SXin Li WhichKind = 0;
601*67e74705SXin Li else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602*67e74705SXin Li WhichKind = 1;
603*67e74705SXin Li else
604*67e74705SXin Li WhichKind = 2;
605*67e74705SXin Li }
606*67e74705SXin Li
607*67e74705SXin Li Diag(NewParam->getLocation(),
608*67e74705SXin Li diag::err_param_default_argument_member_template_redecl)
609*67e74705SXin Li << WhichKind
610*67e74705SXin Li << NewParam->getDefaultArgRange();
611*67e74705SXin Li }
612*67e74705SXin Li }
613*67e74705SXin Li }
614*67e74705SXin Li
615*67e74705SXin Li // DR1344: If a default argument is added outside a class definition and that
616*67e74705SXin Li // default argument makes the function a special member function, the program
617*67e74705SXin Li // is ill-formed. This can only happen for constructors.
618*67e74705SXin Li if (isa<CXXConstructorDecl>(New) &&
619*67e74705SXin Li New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620*67e74705SXin Li CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621*67e74705SXin Li OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622*67e74705SXin Li if (NewSM != OldSM) {
623*67e74705SXin Li ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624*67e74705SXin Li assert(NewParam->hasDefaultArg());
625*67e74705SXin Li Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626*67e74705SXin Li << NewParam->getDefaultArgRange() << NewSM;
627*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_declaration);
628*67e74705SXin Li }
629*67e74705SXin Li }
630*67e74705SXin Li
631*67e74705SXin Li const FunctionDecl *Def;
632*67e74705SXin Li // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633*67e74705SXin Li // template has a constexpr specifier then all its declarations shall
634*67e74705SXin Li // contain the constexpr specifier.
635*67e74705SXin Li if (New->isConstexpr() != Old->isConstexpr()) {
636*67e74705SXin Li Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637*67e74705SXin Li << New << New->isConstexpr();
638*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_declaration);
639*67e74705SXin Li Invalid = true;
640*67e74705SXin Li } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641*67e74705SXin Li Old->isDefined(Def)) {
642*67e74705SXin Li // C++11 [dcl.fcn.spec]p4:
643*67e74705SXin Li // If the definition of a function appears in a translation unit before its
644*67e74705SXin Li // first declaration as inline, the program is ill-formed.
645*67e74705SXin Li Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646*67e74705SXin Li Diag(Def->getLocation(), diag::note_previous_definition);
647*67e74705SXin Li Invalid = true;
648*67e74705SXin Li }
649*67e74705SXin Li
650*67e74705SXin Li // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
651*67e74705SXin Li // argument expression, that declaration shall be a definition and shall be
652*67e74705SXin Li // the only declaration of the function or function template in the
653*67e74705SXin Li // translation unit.
654*67e74705SXin Li if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655*67e74705SXin Li functionDeclHasDefaultArgument(Old)) {
656*67e74705SXin Li Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657*67e74705SXin Li Diag(Old->getLocation(), diag::note_previous_declaration);
658*67e74705SXin Li Invalid = true;
659*67e74705SXin Li }
660*67e74705SXin Li
661*67e74705SXin Li if (CheckEquivalentExceptionSpec(Old, New))
662*67e74705SXin Li Invalid = true;
663*67e74705SXin Li
664*67e74705SXin Li return Invalid;
665*67e74705SXin Li }
666*67e74705SXin Li
667*67e74705SXin Li /// \brief Merge the exception specifications of two variable declarations.
668*67e74705SXin Li ///
669*67e74705SXin Li /// This is called when there's a redeclaration of a VarDecl. The function
670*67e74705SXin Li /// checks if the redeclaration might have an exception specification and
671*67e74705SXin Li /// validates compatibility and merges the specs if necessary.
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)672*67e74705SXin Li void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
673*67e74705SXin Li // Shortcut if exceptions are disabled.
674*67e74705SXin Li if (!getLangOpts().CXXExceptions)
675*67e74705SXin Li return;
676*67e74705SXin Li
677*67e74705SXin Li assert(Context.hasSameType(New->getType(), Old->getType()) &&
678*67e74705SXin Li "Should only be called if types are otherwise the same.");
679*67e74705SXin Li
680*67e74705SXin Li QualType NewType = New->getType();
681*67e74705SXin Li QualType OldType = Old->getType();
682*67e74705SXin Li
683*67e74705SXin Li // We're only interested in pointers and references to functions, as well
684*67e74705SXin Li // as pointers to member functions.
685*67e74705SXin Li if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686*67e74705SXin Li NewType = R->getPointeeType();
687*67e74705SXin Li OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688*67e74705SXin Li } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689*67e74705SXin Li NewType = P->getPointeeType();
690*67e74705SXin Li OldType = OldType->getAs<PointerType>()->getPointeeType();
691*67e74705SXin Li } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692*67e74705SXin Li NewType = M->getPointeeType();
693*67e74705SXin Li OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
694*67e74705SXin Li }
695*67e74705SXin Li
696*67e74705SXin Li if (!NewType->isFunctionProtoType())
697*67e74705SXin Li return;
698*67e74705SXin Li
699*67e74705SXin Li // There's lots of special cases for functions. For function pointers, system
700*67e74705SXin Li // libraries are hopefully not as broken so that we don't need these
701*67e74705SXin Li // workarounds.
702*67e74705SXin Li if (CheckEquivalentExceptionSpec(
703*67e74705SXin Li OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704*67e74705SXin Li NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705*67e74705SXin Li New->setInvalidDecl();
706*67e74705SXin Li }
707*67e74705SXin Li }
708*67e74705SXin Li
709*67e74705SXin Li /// CheckCXXDefaultArguments - Verify that the default arguments for a
710*67e74705SXin Li /// function declaration are well-formed according to C++
711*67e74705SXin Li /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)712*67e74705SXin Li void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
713*67e74705SXin Li unsigned NumParams = FD->getNumParams();
714*67e74705SXin Li unsigned p;
715*67e74705SXin Li
716*67e74705SXin Li // Find first parameter with a default argument
717*67e74705SXin Li for (p = 0; p < NumParams; ++p) {
718*67e74705SXin Li ParmVarDecl *Param = FD->getParamDecl(p);
719*67e74705SXin Li if (Param->hasDefaultArg())
720*67e74705SXin Li break;
721*67e74705SXin Li }
722*67e74705SXin Li
723*67e74705SXin Li // C++11 [dcl.fct.default]p4:
724*67e74705SXin Li // In a given function declaration, each parameter subsequent to a parameter
725*67e74705SXin Li // with a default argument shall have a default argument supplied in this or
726*67e74705SXin Li // a previous declaration or shall be a function parameter pack. A default
727*67e74705SXin Li // argument shall not be redefined by a later declaration (not even to the
728*67e74705SXin Li // same value).
729*67e74705SXin Li unsigned LastMissingDefaultArg = 0;
730*67e74705SXin Li for (; p < NumParams; ++p) {
731*67e74705SXin Li ParmVarDecl *Param = FD->getParamDecl(p);
732*67e74705SXin Li if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
733*67e74705SXin Li if (Param->isInvalidDecl())
734*67e74705SXin Li /* We already complained about this parameter. */;
735*67e74705SXin Li else if (Param->getIdentifier())
736*67e74705SXin Li Diag(Param->getLocation(),
737*67e74705SXin Li diag::err_param_default_argument_missing_name)
738*67e74705SXin Li << Param->getIdentifier();
739*67e74705SXin Li else
740*67e74705SXin Li Diag(Param->getLocation(),
741*67e74705SXin Li diag::err_param_default_argument_missing);
742*67e74705SXin Li
743*67e74705SXin Li LastMissingDefaultArg = p;
744*67e74705SXin Li }
745*67e74705SXin Li }
746*67e74705SXin Li
747*67e74705SXin Li if (LastMissingDefaultArg > 0) {
748*67e74705SXin Li // Some default arguments were missing. Clear out all of the
749*67e74705SXin Li // default arguments up to (and including) the last missing
750*67e74705SXin Li // default argument, so that we leave the function parameters
751*67e74705SXin Li // in a semantically valid state.
752*67e74705SXin Li for (p = 0; p <= LastMissingDefaultArg; ++p) {
753*67e74705SXin Li ParmVarDecl *Param = FD->getParamDecl(p);
754*67e74705SXin Li if (Param->hasDefaultArg()) {
755*67e74705SXin Li Param->setDefaultArg(nullptr);
756*67e74705SXin Li }
757*67e74705SXin Li }
758*67e74705SXin Li }
759*67e74705SXin Li }
760*67e74705SXin Li
761*67e74705SXin Li // CheckConstexprParameterTypes - Check whether a function's parameter types
762*67e74705SXin Li // are all literal types. If so, return true. If not, produce a suitable
763*67e74705SXin Li // diagnostic and return false.
CheckConstexprParameterTypes(Sema & SemaRef,const FunctionDecl * FD)764*67e74705SXin Li static bool CheckConstexprParameterTypes(Sema &SemaRef,
765*67e74705SXin Li const FunctionDecl *FD) {
766*67e74705SXin Li unsigned ArgIndex = 0;
767*67e74705SXin Li const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
768*67e74705SXin Li for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
769*67e74705SXin Li e = FT->param_type_end();
770*67e74705SXin Li i != e; ++i, ++ArgIndex) {
771*67e74705SXin Li const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772*67e74705SXin Li SourceLocation ParamLoc = PD->getLocation();
773*67e74705SXin Li if (!(*i)->isDependentType() &&
774*67e74705SXin Li SemaRef.RequireLiteralType(ParamLoc, *i,
775*67e74705SXin Li diag::err_constexpr_non_literal_param,
776*67e74705SXin Li ArgIndex+1, PD->getSourceRange(),
777*67e74705SXin Li isa<CXXConstructorDecl>(FD)))
778*67e74705SXin Li return false;
779*67e74705SXin Li }
780*67e74705SXin Li return true;
781*67e74705SXin Li }
782*67e74705SXin Li
783*67e74705SXin Li /// \brief Get diagnostic %select index for tag kind for
784*67e74705SXin Li /// record diagnostic message.
785*67e74705SXin Li /// WARNING: Indexes apply to particular diagnostics only!
786*67e74705SXin Li ///
787*67e74705SXin Li /// \returns diagnostic %select index.
getRecordDiagFromTagKind(TagTypeKind Tag)788*67e74705SXin Li static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
789*67e74705SXin Li switch (Tag) {
790*67e74705SXin Li case TTK_Struct: return 0;
791*67e74705SXin Li case TTK_Interface: return 1;
792*67e74705SXin Li case TTK_Class: return 2;
793*67e74705SXin Li default: llvm_unreachable("Invalid tag kind for record diagnostic!");
794*67e74705SXin Li }
795*67e74705SXin Li }
796*67e74705SXin Li
797*67e74705SXin Li // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798*67e74705SXin Li // the requirements of a constexpr function definition or a constexpr
799*67e74705SXin Li // constructor definition. If so, return true. If not, produce appropriate
800*67e74705SXin Li // diagnostics and return false.
801*67e74705SXin Li //
802*67e74705SXin Li // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
CheckConstexprFunctionDecl(const FunctionDecl * NewFD)803*67e74705SXin Li bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
804*67e74705SXin Li const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805*67e74705SXin Li if (MD && MD->isInstance()) {
806*67e74705SXin Li // C++11 [dcl.constexpr]p4:
807*67e74705SXin Li // The definition of a constexpr constructor shall satisfy the following
808*67e74705SXin Li // constraints:
809*67e74705SXin Li // - the class shall not have any virtual base classes;
810*67e74705SXin Li const CXXRecordDecl *RD = MD->getParent();
811*67e74705SXin Li if (RD->getNumVBases()) {
812*67e74705SXin Li Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813*67e74705SXin Li << isa<CXXConstructorDecl>(NewFD)
814*67e74705SXin Li << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
815*67e74705SXin Li for (const auto &I : RD->vbases())
816*67e74705SXin Li Diag(I.getLocStart(),
817*67e74705SXin Li diag::note_constexpr_virtual_base_here) << I.getSourceRange();
818*67e74705SXin Li return false;
819*67e74705SXin Li }
820*67e74705SXin Li }
821*67e74705SXin Li
822*67e74705SXin Li if (!isa<CXXConstructorDecl>(NewFD)) {
823*67e74705SXin Li // C++11 [dcl.constexpr]p3:
824*67e74705SXin Li // The definition of a constexpr function shall satisfy the following
825*67e74705SXin Li // constraints:
826*67e74705SXin Li // - it shall not be virtual;
827*67e74705SXin Li const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828*67e74705SXin Li if (Method && Method->isVirtual()) {
829*67e74705SXin Li Method = Method->getCanonicalDecl();
830*67e74705SXin Li Diag(Method->getLocation(), diag::err_constexpr_virtual);
831*67e74705SXin Li
832*67e74705SXin Li // If it's not obvious why this function is virtual, find an overridden
833*67e74705SXin Li // function which uses the 'virtual' keyword.
834*67e74705SXin Li const CXXMethodDecl *WrittenVirtual = Method;
835*67e74705SXin Li while (!WrittenVirtual->isVirtualAsWritten())
836*67e74705SXin Li WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837*67e74705SXin Li if (WrittenVirtual != Method)
838*67e74705SXin Li Diag(WrittenVirtual->getLocation(),
839*67e74705SXin Li diag::note_overridden_virtual_function);
840*67e74705SXin Li return false;
841*67e74705SXin Li }
842*67e74705SXin Li
843*67e74705SXin Li // - its return type shall be a literal type;
844*67e74705SXin Li QualType RT = NewFD->getReturnType();
845*67e74705SXin Li if (!RT->isDependentType() &&
846*67e74705SXin Li RequireLiteralType(NewFD->getLocation(), RT,
847*67e74705SXin Li diag::err_constexpr_non_literal_return))
848*67e74705SXin Li return false;
849*67e74705SXin Li }
850*67e74705SXin Li
851*67e74705SXin Li // - each of its parameter types shall be a literal type;
852*67e74705SXin Li if (!CheckConstexprParameterTypes(*this, NewFD))
853*67e74705SXin Li return false;
854*67e74705SXin Li
855*67e74705SXin Li return true;
856*67e74705SXin Li }
857*67e74705SXin Li
858*67e74705SXin Li /// Check the given declaration statement is legal within a constexpr function
859*67e74705SXin Li /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
860*67e74705SXin Li ///
861*67e74705SXin Li /// \return true if the body is OK (maybe only as an extension), false if we
862*67e74705SXin Li /// have diagnosed a problem.
CheckConstexprDeclStmt(Sema & SemaRef,const FunctionDecl * Dcl,DeclStmt * DS,SourceLocation & Cxx1yLoc)863*67e74705SXin Li static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
864*67e74705SXin Li DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865*67e74705SXin Li // C++11 [dcl.constexpr]p3 and p4:
866*67e74705SXin Li // The definition of a constexpr function(p3) or constructor(p4) [...] shall
867*67e74705SXin Li // contain only
868*67e74705SXin Li for (const auto *DclIt : DS->decls()) {
869*67e74705SXin Li switch (DclIt->getKind()) {
870*67e74705SXin Li case Decl::StaticAssert:
871*67e74705SXin Li case Decl::Using:
872*67e74705SXin Li case Decl::UsingShadow:
873*67e74705SXin Li case Decl::UsingDirective:
874*67e74705SXin Li case Decl::UnresolvedUsingTypename:
875*67e74705SXin Li case Decl::UnresolvedUsingValue:
876*67e74705SXin Li // - static_assert-declarations
877*67e74705SXin Li // - using-declarations,
878*67e74705SXin Li // - using-directives,
879*67e74705SXin Li continue;
880*67e74705SXin Li
881*67e74705SXin Li case Decl::Typedef:
882*67e74705SXin Li case Decl::TypeAlias: {
883*67e74705SXin Li // - typedef declarations and alias-declarations that do not define
884*67e74705SXin Li // classes or enumerations,
885*67e74705SXin Li const auto *TN = cast<TypedefNameDecl>(DclIt);
886*67e74705SXin Li if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887*67e74705SXin Li // Don't allow variably-modified types in constexpr functions.
888*67e74705SXin Li TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889*67e74705SXin Li SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890*67e74705SXin Li << TL.getSourceRange() << TL.getType()
891*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
892*67e74705SXin Li return false;
893*67e74705SXin Li }
894*67e74705SXin Li continue;
895*67e74705SXin Li }
896*67e74705SXin Li
897*67e74705SXin Li case Decl::Enum:
898*67e74705SXin Li case Decl::CXXRecord:
899*67e74705SXin Li // C++1y allows types to be defined, not just declared.
900*67e74705SXin Li if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
901*67e74705SXin Li SemaRef.Diag(DS->getLocStart(),
902*67e74705SXin Li SemaRef.getLangOpts().CPlusPlus14
903*67e74705SXin Li ? diag::warn_cxx11_compat_constexpr_type_definition
904*67e74705SXin Li : diag::ext_constexpr_type_definition)
905*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
906*67e74705SXin Li continue;
907*67e74705SXin Li
908*67e74705SXin Li case Decl::EnumConstant:
909*67e74705SXin Li case Decl::IndirectField:
910*67e74705SXin Li case Decl::ParmVar:
911*67e74705SXin Li // These can only appear with other declarations which are banned in
912*67e74705SXin Li // C++11 and permitted in C++1y, so ignore them.
913*67e74705SXin Li continue;
914*67e74705SXin Li
915*67e74705SXin Li case Decl::Var: {
916*67e74705SXin Li // C++1y [dcl.constexpr]p3 allows anything except:
917*67e74705SXin Li // a definition of a variable of non-literal type or of static or
918*67e74705SXin Li // thread storage duration or for which no initialization is performed.
919*67e74705SXin Li const auto *VD = cast<VarDecl>(DclIt);
920*67e74705SXin Li if (VD->isThisDeclarationADefinition()) {
921*67e74705SXin Li if (VD->isStaticLocal()) {
922*67e74705SXin Li SemaRef.Diag(VD->getLocation(),
923*67e74705SXin Li diag::err_constexpr_local_var_static)
924*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl)
925*67e74705SXin Li << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
926*67e74705SXin Li return false;
927*67e74705SXin Li }
928*67e74705SXin Li if (!VD->getType()->isDependentType() &&
929*67e74705SXin Li SemaRef.RequireLiteralType(
930*67e74705SXin Li VD->getLocation(), VD->getType(),
931*67e74705SXin Li diag::err_constexpr_local_var_non_literal_type,
932*67e74705SXin Li isa<CXXConstructorDecl>(Dcl)))
933*67e74705SXin Li return false;
934*67e74705SXin Li if (!VD->getType()->isDependentType() &&
935*67e74705SXin Li !VD->hasInit() && !VD->isCXXForRangeDecl()) {
936*67e74705SXin Li SemaRef.Diag(VD->getLocation(),
937*67e74705SXin Li diag::err_constexpr_local_var_no_init)
938*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
939*67e74705SXin Li return false;
940*67e74705SXin Li }
941*67e74705SXin Li }
942*67e74705SXin Li SemaRef.Diag(VD->getLocation(),
943*67e74705SXin Li SemaRef.getLangOpts().CPlusPlus14
944*67e74705SXin Li ? diag::warn_cxx11_compat_constexpr_local_var
945*67e74705SXin Li : diag::ext_constexpr_local_var)
946*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
947*67e74705SXin Li continue;
948*67e74705SXin Li }
949*67e74705SXin Li
950*67e74705SXin Li case Decl::NamespaceAlias:
951*67e74705SXin Li case Decl::Function:
952*67e74705SXin Li // These are disallowed in C++11 and permitted in C++1y. Allow them
953*67e74705SXin Li // everywhere as an extension.
954*67e74705SXin Li if (!Cxx1yLoc.isValid())
955*67e74705SXin Li Cxx1yLoc = DS->getLocStart();
956*67e74705SXin Li continue;
957*67e74705SXin Li
958*67e74705SXin Li default:
959*67e74705SXin Li SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
961*67e74705SXin Li return false;
962*67e74705SXin Li }
963*67e74705SXin Li }
964*67e74705SXin Li
965*67e74705SXin Li return true;
966*67e74705SXin Li }
967*67e74705SXin Li
968*67e74705SXin Li /// Check that the given field is initialized within a constexpr constructor.
969*67e74705SXin Li ///
970*67e74705SXin Li /// \param Dcl The constexpr constructor being checked.
971*67e74705SXin Li /// \param Field The field being checked. This may be a member of an anonymous
972*67e74705SXin Li /// struct or union nested within the class being checked.
973*67e74705SXin Li /// \param Inits All declarations, including anonymous struct/union members and
974*67e74705SXin Li /// indirect members, for which any initialization was provided.
975*67e74705SXin Li /// \param Diagnosed Set to true if an error is produced.
CheckConstexprCtorInitializer(Sema & SemaRef,const FunctionDecl * Dcl,FieldDecl * Field,llvm::SmallSet<Decl *,16> & Inits,bool & Diagnosed)976*67e74705SXin Li static void CheckConstexprCtorInitializer(Sema &SemaRef,
977*67e74705SXin Li const FunctionDecl *Dcl,
978*67e74705SXin Li FieldDecl *Field,
979*67e74705SXin Li llvm::SmallSet<Decl*, 16> &Inits,
980*67e74705SXin Li bool &Diagnosed) {
981*67e74705SXin Li if (Field->isInvalidDecl())
982*67e74705SXin Li return;
983*67e74705SXin Li
984*67e74705SXin Li if (Field->isUnnamedBitfield())
985*67e74705SXin Li return;
986*67e74705SXin Li
987*67e74705SXin Li // Anonymous unions with no variant members and empty anonymous structs do not
988*67e74705SXin Li // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989*67e74705SXin Li // indirect fields don't need initializing.
990*67e74705SXin Li if (Field->isAnonymousStructOrUnion() &&
991*67e74705SXin Li (Field->getType()->isUnionType()
992*67e74705SXin Li ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
993*67e74705SXin Li : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
994*67e74705SXin Li return;
995*67e74705SXin Li
996*67e74705SXin Li if (!Inits.count(Field)) {
997*67e74705SXin Li if (!Diagnosed) {
998*67e74705SXin Li SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
999*67e74705SXin Li Diagnosed = true;
1000*67e74705SXin Li }
1001*67e74705SXin Li SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002*67e74705SXin Li } else if (Field->isAnonymousStructOrUnion()) {
1003*67e74705SXin Li const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1004*67e74705SXin Li for (auto *I : RD->fields())
1005*67e74705SXin Li // If an anonymous union contains an anonymous struct of which any member
1006*67e74705SXin Li // is initialized, all members must be initialized.
1007*67e74705SXin Li if (!RD->isUnion() || Inits.count(I))
1008*67e74705SXin Li CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1009*67e74705SXin Li }
1010*67e74705SXin Li }
1011*67e74705SXin Li
1012*67e74705SXin Li /// Check the provided statement is allowed in a constexpr function
1013*67e74705SXin Li /// definition.
1014*67e74705SXin Li static bool
CheckConstexprFunctionStmt(Sema & SemaRef,const FunctionDecl * Dcl,Stmt * S,SmallVectorImpl<SourceLocation> & ReturnStmts,SourceLocation & Cxx1yLoc)1015*67e74705SXin Li CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1016*67e74705SXin Li SmallVectorImpl<SourceLocation> &ReturnStmts,
1017*67e74705SXin Li SourceLocation &Cxx1yLoc) {
1018*67e74705SXin Li // - its function-body shall be [...] a compound-statement that contains only
1019*67e74705SXin Li switch (S->getStmtClass()) {
1020*67e74705SXin Li case Stmt::NullStmtClass:
1021*67e74705SXin Li // - null statements,
1022*67e74705SXin Li return true;
1023*67e74705SXin Li
1024*67e74705SXin Li case Stmt::DeclStmtClass:
1025*67e74705SXin Li // - static_assert-declarations
1026*67e74705SXin Li // - using-declarations,
1027*67e74705SXin Li // - using-directives,
1028*67e74705SXin Li // - typedef declarations and alias-declarations that do not define
1029*67e74705SXin Li // classes or enumerations,
1030*67e74705SXin Li if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1031*67e74705SXin Li return false;
1032*67e74705SXin Li return true;
1033*67e74705SXin Li
1034*67e74705SXin Li case Stmt::ReturnStmtClass:
1035*67e74705SXin Li // - and exactly one return statement;
1036*67e74705SXin Li if (isa<CXXConstructorDecl>(Dcl)) {
1037*67e74705SXin Li // C++1y allows return statements in constexpr constructors.
1038*67e74705SXin Li if (!Cxx1yLoc.isValid())
1039*67e74705SXin Li Cxx1yLoc = S->getLocStart();
1040*67e74705SXin Li return true;
1041*67e74705SXin Li }
1042*67e74705SXin Li
1043*67e74705SXin Li ReturnStmts.push_back(S->getLocStart());
1044*67e74705SXin Li return true;
1045*67e74705SXin Li
1046*67e74705SXin Li case Stmt::CompoundStmtClass: {
1047*67e74705SXin Li // C++1y allows compound-statements.
1048*67e74705SXin Li if (!Cxx1yLoc.isValid())
1049*67e74705SXin Li Cxx1yLoc = S->getLocStart();
1050*67e74705SXin Li
1051*67e74705SXin Li CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1052*67e74705SXin Li for (auto *BodyIt : CompStmt->body()) {
1053*67e74705SXin Li if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1054*67e74705SXin Li Cxx1yLoc))
1055*67e74705SXin Li return false;
1056*67e74705SXin Li }
1057*67e74705SXin Li return true;
1058*67e74705SXin Li }
1059*67e74705SXin Li
1060*67e74705SXin Li case Stmt::AttributedStmtClass:
1061*67e74705SXin Li if (!Cxx1yLoc.isValid())
1062*67e74705SXin Li Cxx1yLoc = S->getLocStart();
1063*67e74705SXin Li return true;
1064*67e74705SXin Li
1065*67e74705SXin Li case Stmt::IfStmtClass: {
1066*67e74705SXin Li // C++1y allows if-statements.
1067*67e74705SXin Li if (!Cxx1yLoc.isValid())
1068*67e74705SXin Li Cxx1yLoc = S->getLocStart();
1069*67e74705SXin Li
1070*67e74705SXin Li IfStmt *If = cast<IfStmt>(S);
1071*67e74705SXin Li if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1072*67e74705SXin Li Cxx1yLoc))
1073*67e74705SXin Li return false;
1074*67e74705SXin Li if (If->getElse() &&
1075*67e74705SXin Li !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1076*67e74705SXin Li Cxx1yLoc))
1077*67e74705SXin Li return false;
1078*67e74705SXin Li return true;
1079*67e74705SXin Li }
1080*67e74705SXin Li
1081*67e74705SXin Li case Stmt::WhileStmtClass:
1082*67e74705SXin Li case Stmt::DoStmtClass:
1083*67e74705SXin Li case Stmt::ForStmtClass:
1084*67e74705SXin Li case Stmt::CXXForRangeStmtClass:
1085*67e74705SXin Li case Stmt::ContinueStmtClass:
1086*67e74705SXin Li // C++1y allows all of these. We don't allow them as extensions in C++11,
1087*67e74705SXin Li // because they don't make sense without variable mutation.
1088*67e74705SXin Li if (!SemaRef.getLangOpts().CPlusPlus14)
1089*67e74705SXin Li break;
1090*67e74705SXin Li if (!Cxx1yLoc.isValid())
1091*67e74705SXin Li Cxx1yLoc = S->getLocStart();
1092*67e74705SXin Li for (Stmt *SubStmt : S->children())
1093*67e74705SXin Li if (SubStmt &&
1094*67e74705SXin Li !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1095*67e74705SXin Li Cxx1yLoc))
1096*67e74705SXin Li return false;
1097*67e74705SXin Li return true;
1098*67e74705SXin Li
1099*67e74705SXin Li case Stmt::SwitchStmtClass:
1100*67e74705SXin Li case Stmt::CaseStmtClass:
1101*67e74705SXin Li case Stmt::DefaultStmtClass:
1102*67e74705SXin Li case Stmt::BreakStmtClass:
1103*67e74705SXin Li // C++1y allows switch-statements, and since they don't need variable
1104*67e74705SXin Li // mutation, we can reasonably allow them in C++11 as an extension.
1105*67e74705SXin Li if (!Cxx1yLoc.isValid())
1106*67e74705SXin Li Cxx1yLoc = S->getLocStart();
1107*67e74705SXin Li for (Stmt *SubStmt : S->children())
1108*67e74705SXin Li if (SubStmt &&
1109*67e74705SXin Li !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1110*67e74705SXin Li Cxx1yLoc))
1111*67e74705SXin Li return false;
1112*67e74705SXin Li return true;
1113*67e74705SXin Li
1114*67e74705SXin Li default:
1115*67e74705SXin Li if (!isa<Expr>(S))
1116*67e74705SXin Li break;
1117*67e74705SXin Li
1118*67e74705SXin Li // C++1y allows expression-statements.
1119*67e74705SXin Li if (!Cxx1yLoc.isValid())
1120*67e74705SXin Li Cxx1yLoc = S->getLocStart();
1121*67e74705SXin Li return true;
1122*67e74705SXin Li }
1123*67e74705SXin Li
1124*67e74705SXin Li SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
1126*67e74705SXin Li return false;
1127*67e74705SXin Li }
1128*67e74705SXin Li
1129*67e74705SXin Li /// Check the body for the given constexpr function declaration only contains
1130*67e74705SXin Li /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1131*67e74705SXin Li ///
1132*67e74705SXin Li /// \return true if the body is OK, false if we have diagnosed a problem.
CheckConstexprFunctionBody(const FunctionDecl * Dcl,Stmt * Body)1133*67e74705SXin Li bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1134*67e74705SXin Li if (isa<CXXTryStmt>(Body)) {
1135*67e74705SXin Li // C++11 [dcl.constexpr]p3:
1136*67e74705SXin Li // The definition of a constexpr function shall satisfy the following
1137*67e74705SXin Li // constraints: [...]
1138*67e74705SXin Li // - its function-body shall be = delete, = default, or a
1139*67e74705SXin Li // compound-statement
1140*67e74705SXin Li //
1141*67e74705SXin Li // C++11 [dcl.constexpr]p4:
1142*67e74705SXin Li // In the definition of a constexpr constructor, [...]
1143*67e74705SXin Li // - its function-body shall not be a function-try-block;
1144*67e74705SXin Li Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
1146*67e74705SXin Li return false;
1147*67e74705SXin Li }
1148*67e74705SXin Li
1149*67e74705SXin Li SmallVector<SourceLocation, 4> ReturnStmts;
1150*67e74705SXin Li
1151*67e74705SXin Li // - its function-body shall be [...] a compound-statement that contains only
1152*67e74705SXin Li // [... list of cases ...]
1153*67e74705SXin Li CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154*67e74705SXin Li SourceLocation Cxx1yLoc;
1155*67e74705SXin Li for (auto *BodyIt : CompBody->body()) {
1156*67e74705SXin Li if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1157*67e74705SXin Li return false;
1158*67e74705SXin Li }
1159*67e74705SXin Li
1160*67e74705SXin Li if (Cxx1yLoc.isValid())
1161*67e74705SXin Li Diag(Cxx1yLoc,
1162*67e74705SXin Li getLangOpts().CPlusPlus14
1163*67e74705SXin Li ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164*67e74705SXin Li : diag::ext_constexpr_body_invalid_stmt)
1165*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
1166*67e74705SXin Li
1167*67e74705SXin Li if (const CXXConstructorDecl *Constructor
1168*67e74705SXin Li = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169*67e74705SXin Li const CXXRecordDecl *RD = Constructor->getParent();
1170*67e74705SXin Li // DR1359:
1171*67e74705SXin Li // - every non-variant non-static data member and base class sub-object
1172*67e74705SXin Li // shall be initialized;
1173*67e74705SXin Li // DR1460:
1174*67e74705SXin Li // - if the class is a union having variant members, exactly one of them
1175*67e74705SXin Li // shall be initialized;
1176*67e74705SXin Li if (RD->isUnion()) {
1177*67e74705SXin Li if (Constructor->getNumCtorInitializers() == 0 &&
1178*67e74705SXin Li RD->hasVariantMembers()) {
1179*67e74705SXin Li Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1180*67e74705SXin Li return false;
1181*67e74705SXin Li }
1182*67e74705SXin Li } else if (!Constructor->isDependentContext() &&
1183*67e74705SXin Li !Constructor->isDelegatingConstructor()) {
1184*67e74705SXin Li assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1185*67e74705SXin Li
1186*67e74705SXin Li // Skip detailed checking if we have enough initializers, and we would
1187*67e74705SXin Li // allow at most one initializer per member.
1188*67e74705SXin Li bool AnyAnonStructUnionMembers = false;
1189*67e74705SXin Li unsigned Fields = 0;
1190*67e74705SXin Li for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1191*67e74705SXin Li E = RD->field_end(); I != E; ++I, ++Fields) {
1192*67e74705SXin Li if (I->isAnonymousStructOrUnion()) {
1193*67e74705SXin Li AnyAnonStructUnionMembers = true;
1194*67e74705SXin Li break;
1195*67e74705SXin Li }
1196*67e74705SXin Li }
1197*67e74705SXin Li // DR1460:
1198*67e74705SXin Li // - if the class is a union-like class, but is not a union, for each of
1199*67e74705SXin Li // its anonymous union members having variant members, exactly one of
1200*67e74705SXin Li // them shall be initialized;
1201*67e74705SXin Li if (AnyAnonStructUnionMembers ||
1202*67e74705SXin Li Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203*67e74705SXin Li // Check initialization of non-static data members. Base classes are
1204*67e74705SXin Li // always initialized so do not need to be checked. Dependent bases
1205*67e74705SXin Li // might not have initializers in the member initializer list.
1206*67e74705SXin Li llvm::SmallSet<Decl*, 16> Inits;
1207*67e74705SXin Li for (const auto *I: Constructor->inits()) {
1208*67e74705SXin Li if (FieldDecl *FD = I->getMember())
1209*67e74705SXin Li Inits.insert(FD);
1210*67e74705SXin Li else if (IndirectFieldDecl *ID = I->getIndirectMember())
1211*67e74705SXin Li Inits.insert(ID->chain_begin(), ID->chain_end());
1212*67e74705SXin Li }
1213*67e74705SXin Li
1214*67e74705SXin Li bool Diagnosed = false;
1215*67e74705SXin Li for (auto *I : RD->fields())
1216*67e74705SXin Li CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1217*67e74705SXin Li if (Diagnosed)
1218*67e74705SXin Li return false;
1219*67e74705SXin Li }
1220*67e74705SXin Li }
1221*67e74705SXin Li } else {
1222*67e74705SXin Li if (ReturnStmts.empty()) {
1223*67e74705SXin Li // C++1y doesn't require constexpr functions to contain a 'return'
1224*67e74705SXin Li // statement. We still do, unless the return type might be void, because
1225*67e74705SXin Li // otherwise if there's no return statement, the function cannot
1226*67e74705SXin Li // be used in a core constant expression.
1227*67e74705SXin Li bool OK = getLangOpts().CPlusPlus14 &&
1228*67e74705SXin Li (Dcl->getReturnType()->isVoidType() ||
1229*67e74705SXin Li Dcl->getReturnType()->isDependentType());
1230*67e74705SXin Li Diag(Dcl->getLocation(),
1231*67e74705SXin Li OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232*67e74705SXin Li : diag::err_constexpr_body_no_return);
1233*67e74705SXin Li if (!OK)
1234*67e74705SXin Li return false;
1235*67e74705SXin Li } else if (ReturnStmts.size() > 1) {
1236*67e74705SXin Li Diag(ReturnStmts.back(),
1237*67e74705SXin Li getLangOpts().CPlusPlus14
1238*67e74705SXin Li ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239*67e74705SXin Li : diag::ext_constexpr_body_multiple_return);
1240*67e74705SXin Li for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241*67e74705SXin Li Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1242*67e74705SXin Li }
1243*67e74705SXin Li }
1244*67e74705SXin Li
1245*67e74705SXin Li // C++11 [dcl.constexpr]p5:
1246*67e74705SXin Li // if no function argument values exist such that the function invocation
1247*67e74705SXin Li // substitution would produce a constant expression, the program is
1248*67e74705SXin Li // ill-formed; no diagnostic required.
1249*67e74705SXin Li // C++11 [dcl.constexpr]p3:
1250*67e74705SXin Li // - every constructor call and implicit conversion used in initializing the
1251*67e74705SXin Li // return value shall be one of those allowed in a constant expression.
1252*67e74705SXin Li // C++11 [dcl.constexpr]p4:
1253*67e74705SXin Li // - every constructor involved in initializing non-static data members and
1254*67e74705SXin Li // base class sub-objects shall be a constexpr constructor.
1255*67e74705SXin Li SmallVector<PartialDiagnosticAt, 8> Diags;
1256*67e74705SXin Li if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1257*67e74705SXin Li Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1258*67e74705SXin Li << isa<CXXConstructorDecl>(Dcl);
1259*67e74705SXin Li for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260*67e74705SXin Li Diag(Diags[I].first, Diags[I].second);
1261*67e74705SXin Li // Don't return false here: we allow this for compatibility in
1262*67e74705SXin Li // system headers.
1263*67e74705SXin Li }
1264*67e74705SXin Li
1265*67e74705SXin Li return true;
1266*67e74705SXin Li }
1267*67e74705SXin Li
1268*67e74705SXin Li /// isCurrentClassName - Determine whether the identifier II is the
1269*67e74705SXin Li /// name of the class type currently being defined. In the case of
1270*67e74705SXin Li /// nested classes, this will only return true if II is the name of
1271*67e74705SXin Li /// the innermost class.
isCurrentClassName(const IdentifierInfo & II,Scope *,const CXXScopeSpec * SS)1272*67e74705SXin Li bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1273*67e74705SXin Li const CXXScopeSpec *SS) {
1274*67e74705SXin Li assert(getLangOpts().CPlusPlus && "No class names in C!");
1275*67e74705SXin Li
1276*67e74705SXin Li CXXRecordDecl *CurDecl;
1277*67e74705SXin Li if (SS && SS->isSet() && !SS->isInvalid()) {
1278*67e74705SXin Li DeclContext *DC = computeDeclContext(*SS, true);
1279*67e74705SXin Li CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1280*67e74705SXin Li } else
1281*67e74705SXin Li CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1282*67e74705SXin Li
1283*67e74705SXin Li if (CurDecl && CurDecl->getIdentifier())
1284*67e74705SXin Li return &II == CurDecl->getIdentifier();
1285*67e74705SXin Li return false;
1286*67e74705SXin Li }
1287*67e74705SXin Li
1288*67e74705SXin Li /// \brief Determine whether the identifier II is a typo for the name of
1289*67e74705SXin Li /// the class type currently being defined. If so, update it to the identifier
1290*67e74705SXin Li /// that should have been used.
isCurrentClassNameTypo(IdentifierInfo * & II,const CXXScopeSpec * SS)1291*67e74705SXin Li bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1292*67e74705SXin Li assert(getLangOpts().CPlusPlus && "No class names in C!");
1293*67e74705SXin Li
1294*67e74705SXin Li if (!getLangOpts().SpellChecking)
1295*67e74705SXin Li return false;
1296*67e74705SXin Li
1297*67e74705SXin Li CXXRecordDecl *CurDecl;
1298*67e74705SXin Li if (SS && SS->isSet() && !SS->isInvalid()) {
1299*67e74705SXin Li DeclContext *DC = computeDeclContext(*SS, true);
1300*67e74705SXin Li CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1301*67e74705SXin Li } else
1302*67e74705SXin Li CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1303*67e74705SXin Li
1304*67e74705SXin Li if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305*67e74705SXin Li 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306*67e74705SXin Li < II->getLength()) {
1307*67e74705SXin Li II = CurDecl->getIdentifier();
1308*67e74705SXin Li return true;
1309*67e74705SXin Li }
1310*67e74705SXin Li
1311*67e74705SXin Li return false;
1312*67e74705SXin Li }
1313*67e74705SXin Li
1314*67e74705SXin Li /// \brief Determine whether the given class is a base class of the given
1315*67e74705SXin Li /// class, including looking at dependent bases.
findCircularInheritance(const CXXRecordDecl * Class,const CXXRecordDecl * Current)1316*67e74705SXin Li static bool findCircularInheritance(const CXXRecordDecl *Class,
1317*67e74705SXin Li const CXXRecordDecl *Current) {
1318*67e74705SXin Li SmallVector<const CXXRecordDecl*, 8> Queue;
1319*67e74705SXin Li
1320*67e74705SXin Li Class = Class->getCanonicalDecl();
1321*67e74705SXin Li while (true) {
1322*67e74705SXin Li for (const auto &I : Current->bases()) {
1323*67e74705SXin Li CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1324*67e74705SXin Li if (!Base)
1325*67e74705SXin Li continue;
1326*67e74705SXin Li
1327*67e74705SXin Li Base = Base->getDefinition();
1328*67e74705SXin Li if (!Base)
1329*67e74705SXin Li continue;
1330*67e74705SXin Li
1331*67e74705SXin Li if (Base->getCanonicalDecl() == Class)
1332*67e74705SXin Li return true;
1333*67e74705SXin Li
1334*67e74705SXin Li Queue.push_back(Base);
1335*67e74705SXin Li }
1336*67e74705SXin Li
1337*67e74705SXin Li if (Queue.empty())
1338*67e74705SXin Li return false;
1339*67e74705SXin Li
1340*67e74705SXin Li Current = Queue.pop_back_val();
1341*67e74705SXin Li }
1342*67e74705SXin Li
1343*67e74705SXin Li return false;
1344*67e74705SXin Li }
1345*67e74705SXin Li
1346*67e74705SXin Li /// \brief Check the validity of a C++ base class specifier.
1347*67e74705SXin Li ///
1348*67e74705SXin Li /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349*67e74705SXin Li /// and returns NULL otherwise.
1350*67e74705SXin Li CXXBaseSpecifier *
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)1351*67e74705SXin Li Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1352*67e74705SXin Li SourceRange SpecifierRange,
1353*67e74705SXin Li bool Virtual, AccessSpecifier Access,
1354*67e74705SXin Li TypeSourceInfo *TInfo,
1355*67e74705SXin Li SourceLocation EllipsisLoc) {
1356*67e74705SXin Li QualType BaseType = TInfo->getType();
1357*67e74705SXin Li
1358*67e74705SXin Li // C++ [class.union]p1:
1359*67e74705SXin Li // A union shall not have base classes.
1360*67e74705SXin Li if (Class->isUnion()) {
1361*67e74705SXin Li Diag(Class->getLocation(), diag::err_base_clause_on_union)
1362*67e74705SXin Li << SpecifierRange;
1363*67e74705SXin Li return nullptr;
1364*67e74705SXin Li }
1365*67e74705SXin Li
1366*67e74705SXin Li if (EllipsisLoc.isValid() &&
1367*67e74705SXin Li !TInfo->getType()->containsUnexpandedParameterPack()) {
1368*67e74705SXin Li Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369*67e74705SXin Li << TInfo->getTypeLoc().getSourceRange();
1370*67e74705SXin Li EllipsisLoc = SourceLocation();
1371*67e74705SXin Li }
1372*67e74705SXin Li
1373*67e74705SXin Li SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1374*67e74705SXin Li
1375*67e74705SXin Li if (BaseType->isDependentType()) {
1376*67e74705SXin Li // Make sure that we don't have circular inheritance among our dependent
1377*67e74705SXin Li // bases. For non-dependent bases, the check for completeness below handles
1378*67e74705SXin Li // this.
1379*67e74705SXin Li if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380*67e74705SXin Li if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381*67e74705SXin Li ((BaseDecl = BaseDecl->getDefinition()) &&
1382*67e74705SXin Li findCircularInheritance(Class, BaseDecl))) {
1383*67e74705SXin Li Diag(BaseLoc, diag::err_circular_inheritance)
1384*67e74705SXin Li << BaseType << Context.getTypeDeclType(Class);
1385*67e74705SXin Li
1386*67e74705SXin Li if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387*67e74705SXin Li Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1388*67e74705SXin Li << BaseType;
1389*67e74705SXin Li
1390*67e74705SXin Li return nullptr;
1391*67e74705SXin Li }
1392*67e74705SXin Li }
1393*67e74705SXin Li
1394*67e74705SXin Li return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1395*67e74705SXin Li Class->getTagKind() == TTK_Class,
1396*67e74705SXin Li Access, TInfo, EllipsisLoc);
1397*67e74705SXin Li }
1398*67e74705SXin Li
1399*67e74705SXin Li // Base specifiers must be record types.
1400*67e74705SXin Li if (!BaseType->isRecordType()) {
1401*67e74705SXin Li Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1402*67e74705SXin Li return nullptr;
1403*67e74705SXin Li }
1404*67e74705SXin Li
1405*67e74705SXin Li // C++ [class.union]p1:
1406*67e74705SXin Li // A union shall not be used as a base class.
1407*67e74705SXin Li if (BaseType->isUnionType()) {
1408*67e74705SXin Li Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1409*67e74705SXin Li return nullptr;
1410*67e74705SXin Li }
1411*67e74705SXin Li
1412*67e74705SXin Li // For the MS ABI, propagate DLL attributes to base class templates.
1413*67e74705SXin Li if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1414*67e74705SXin Li if (Attr *ClassAttr = getDLLAttr(Class)) {
1415*67e74705SXin Li if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416*67e74705SXin Li BaseType->getAsCXXRecordDecl())) {
1417*67e74705SXin Li propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1418*67e74705SXin Li BaseLoc);
1419*67e74705SXin Li }
1420*67e74705SXin Li }
1421*67e74705SXin Li }
1422*67e74705SXin Li
1423*67e74705SXin Li // C++ [class.derived]p2:
1424*67e74705SXin Li // The class-name in a base-specifier shall not be an incompletely
1425*67e74705SXin Li // defined class.
1426*67e74705SXin Li if (RequireCompleteType(BaseLoc, BaseType,
1427*67e74705SXin Li diag::err_incomplete_base_class, SpecifierRange)) {
1428*67e74705SXin Li Class->setInvalidDecl();
1429*67e74705SXin Li return nullptr;
1430*67e74705SXin Li }
1431*67e74705SXin Li
1432*67e74705SXin Li // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1433*67e74705SXin Li RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1434*67e74705SXin Li assert(BaseDecl && "Record type has no declaration");
1435*67e74705SXin Li BaseDecl = BaseDecl->getDefinition();
1436*67e74705SXin Li assert(BaseDecl && "Base type is not incomplete, but has no definition");
1437*67e74705SXin Li CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1438*67e74705SXin Li assert(CXXBaseDecl && "Base type is not a C++ type");
1439*67e74705SXin Li
1440*67e74705SXin Li // A class which contains a flexible array member is not suitable for use as a
1441*67e74705SXin Li // base class:
1442*67e74705SXin Li // - If the layout determines that a base comes before another base,
1443*67e74705SXin Li // the flexible array member would index into the subsequent base.
1444*67e74705SXin Li // - If the layout determines that base comes before the derived class,
1445*67e74705SXin Li // the flexible array member would index into the derived class.
1446*67e74705SXin Li if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447*67e74705SXin Li Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448*67e74705SXin Li << CXXBaseDecl->getDeclName();
1449*67e74705SXin Li return nullptr;
1450*67e74705SXin Li }
1451*67e74705SXin Li
1452*67e74705SXin Li // C++ [class]p3:
1453*67e74705SXin Li // If a class is marked final and it appears as a base-type-specifier in
1454*67e74705SXin Li // base-clause, the program is ill-formed.
1455*67e74705SXin Li if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1456*67e74705SXin Li Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1457*67e74705SXin Li << CXXBaseDecl->getDeclName()
1458*67e74705SXin Li << FA->isSpelledAsSealed();
1459*67e74705SXin Li Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460*67e74705SXin Li << CXXBaseDecl->getDeclName() << FA->getRange();
1461*67e74705SXin Li return nullptr;
1462*67e74705SXin Li }
1463*67e74705SXin Li
1464*67e74705SXin Li if (BaseDecl->isInvalidDecl())
1465*67e74705SXin Li Class->setInvalidDecl();
1466*67e74705SXin Li
1467*67e74705SXin Li // Create the base specifier.
1468*67e74705SXin Li return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1469*67e74705SXin Li Class->getTagKind() == TTK_Class,
1470*67e74705SXin Li Access, TInfo, EllipsisLoc);
1471*67e74705SXin Li }
1472*67e74705SXin Li
1473*67e74705SXin Li /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474*67e74705SXin Li /// one entry in the base class list of a class specifier, for
1475*67e74705SXin Li /// example:
1476*67e74705SXin Li /// class foo : public bar, virtual private baz {
1477*67e74705SXin Li /// 'public bar' and 'virtual private baz' are each base-specifiers.
1478*67e74705SXin Li BaseResult
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,ParsedAttributes & Attributes,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)1479*67e74705SXin Li Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1480*67e74705SXin Li ParsedAttributes &Attributes,
1481*67e74705SXin Li bool Virtual, AccessSpecifier Access,
1482*67e74705SXin Li ParsedType basetype, SourceLocation BaseLoc,
1483*67e74705SXin Li SourceLocation EllipsisLoc) {
1484*67e74705SXin Li if (!classdecl)
1485*67e74705SXin Li return true;
1486*67e74705SXin Li
1487*67e74705SXin Li AdjustDeclIfTemplate(classdecl);
1488*67e74705SXin Li CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1489*67e74705SXin Li if (!Class)
1490*67e74705SXin Li return true;
1491*67e74705SXin Li
1492*67e74705SXin Li // We haven't yet attached the base specifiers.
1493*67e74705SXin Li Class->setIsParsingBaseSpecifiers();
1494*67e74705SXin Li
1495*67e74705SXin Li // We do not support any C++11 attributes on base-specifiers yet.
1496*67e74705SXin Li // Diagnose any attributes we see.
1497*67e74705SXin Li if (!Attributes.empty()) {
1498*67e74705SXin Li for (AttributeList *Attr = Attributes.getList(); Attr;
1499*67e74705SXin Li Attr = Attr->getNext()) {
1500*67e74705SXin Li if (Attr->isInvalid() ||
1501*67e74705SXin Li Attr->getKind() == AttributeList::IgnoredAttribute)
1502*67e74705SXin Li continue;
1503*67e74705SXin Li Diag(Attr->getLoc(),
1504*67e74705SXin Li Attr->getKind() == AttributeList::UnknownAttribute
1505*67e74705SXin Li ? diag::warn_unknown_attribute_ignored
1506*67e74705SXin Li : diag::err_base_specifier_attribute)
1507*67e74705SXin Li << Attr->getName();
1508*67e74705SXin Li }
1509*67e74705SXin Li }
1510*67e74705SXin Li
1511*67e74705SXin Li TypeSourceInfo *TInfo = nullptr;
1512*67e74705SXin Li GetTypeFromParser(basetype, &TInfo);
1513*67e74705SXin Li
1514*67e74705SXin Li if (EllipsisLoc.isInvalid() &&
1515*67e74705SXin Li DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1516*67e74705SXin Li UPPC_BaseType))
1517*67e74705SXin Li return true;
1518*67e74705SXin Li
1519*67e74705SXin Li if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1520*67e74705SXin Li Virtual, Access, TInfo,
1521*67e74705SXin Li EllipsisLoc))
1522*67e74705SXin Li return BaseSpec;
1523*67e74705SXin Li else
1524*67e74705SXin Li Class->setInvalidDecl();
1525*67e74705SXin Li
1526*67e74705SXin Li return true;
1527*67e74705SXin Li }
1528*67e74705SXin Li
1529*67e74705SXin Li /// Use small set to collect indirect bases. As this is only used
1530*67e74705SXin Li /// locally, there's no need to abstract the small size parameter.
1531*67e74705SXin Li typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1532*67e74705SXin Li
1533*67e74705SXin Li /// \brief Recursively add the bases of Type. Don't add Type itself.
1534*67e74705SXin Li static void
NoteIndirectBases(ASTContext & Context,IndirectBaseSet & Set,const QualType & Type)1535*67e74705SXin Li NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1536*67e74705SXin Li const QualType &Type)
1537*67e74705SXin Li {
1538*67e74705SXin Li // Even though the incoming type is a base, it might not be
1539*67e74705SXin Li // a class -- it could be a template parm, for instance.
1540*67e74705SXin Li if (auto Rec = Type->getAs<RecordType>()) {
1541*67e74705SXin Li auto Decl = Rec->getAsCXXRecordDecl();
1542*67e74705SXin Li
1543*67e74705SXin Li // Iterate over its bases.
1544*67e74705SXin Li for (const auto &BaseSpec : Decl->bases()) {
1545*67e74705SXin Li QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546*67e74705SXin Li .getUnqualifiedType();
1547*67e74705SXin Li if (Set.insert(Base).second)
1548*67e74705SXin Li // If we've not already seen it, recurse.
1549*67e74705SXin Li NoteIndirectBases(Context, Set, Base);
1550*67e74705SXin Li }
1551*67e74705SXin Li }
1552*67e74705SXin Li }
1553*67e74705SXin Li
1554*67e74705SXin Li /// \brief Performs the actual work of attaching the given base class
1555*67e74705SXin Li /// specifiers to a C++ class.
AttachBaseSpecifiers(CXXRecordDecl * Class,MutableArrayRef<CXXBaseSpecifier * > Bases)1556*67e74705SXin Li bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
1557*67e74705SXin Li MutableArrayRef<CXXBaseSpecifier *> Bases) {
1558*67e74705SXin Li if (Bases.empty())
1559*67e74705SXin Li return false;
1560*67e74705SXin Li
1561*67e74705SXin Li // Used to keep track of which base types we have already seen, so
1562*67e74705SXin Li // that we can properly diagnose redundant direct base types. Note
1563*67e74705SXin Li // that the key is always the unqualified canonical type of the base
1564*67e74705SXin Li // class.
1565*67e74705SXin Li std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1566*67e74705SXin Li
1567*67e74705SXin Li // Used to track indirect bases so we can see if a direct base is
1568*67e74705SXin Li // ambiguous.
1569*67e74705SXin Li IndirectBaseSet IndirectBaseTypes;
1570*67e74705SXin Li
1571*67e74705SXin Li // Copy non-redundant base specifiers into permanent storage.
1572*67e74705SXin Li unsigned NumGoodBases = 0;
1573*67e74705SXin Li bool Invalid = false;
1574*67e74705SXin Li for (unsigned idx = 0; idx < Bases.size(); ++idx) {
1575*67e74705SXin Li QualType NewBaseType
1576*67e74705SXin Li = Context.getCanonicalType(Bases[idx]->getType());
1577*67e74705SXin Li NewBaseType = NewBaseType.getLocalUnqualifiedType();
1578*67e74705SXin Li
1579*67e74705SXin Li CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1580*67e74705SXin Li if (KnownBase) {
1581*67e74705SXin Li // C++ [class.mi]p3:
1582*67e74705SXin Li // A class shall not be specified as a direct base class of a
1583*67e74705SXin Li // derived class more than once.
1584*67e74705SXin Li Diag(Bases[idx]->getLocStart(),
1585*67e74705SXin Li diag::err_duplicate_base_class)
1586*67e74705SXin Li << KnownBase->getType()
1587*67e74705SXin Li << Bases[idx]->getSourceRange();
1588*67e74705SXin Li
1589*67e74705SXin Li // Delete the duplicate base class specifier; we're going to
1590*67e74705SXin Li // overwrite its pointer later.
1591*67e74705SXin Li Context.Deallocate(Bases[idx]);
1592*67e74705SXin Li
1593*67e74705SXin Li Invalid = true;
1594*67e74705SXin Li } else {
1595*67e74705SXin Li // Okay, add this new base class.
1596*67e74705SXin Li KnownBase = Bases[idx];
1597*67e74705SXin Li Bases[NumGoodBases++] = Bases[idx];
1598*67e74705SXin Li
1599*67e74705SXin Li // Note this base's direct & indirect bases, if there could be ambiguity.
1600*67e74705SXin Li if (Bases.size() > 1)
1601*67e74705SXin Li NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1602*67e74705SXin Li
1603*67e74705SXin Li if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604*67e74705SXin Li const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605*67e74705SXin Li if (Class->isInterface() &&
1606*67e74705SXin Li (!RD->isInterface() ||
1607*67e74705SXin Li KnownBase->getAccessSpecifier() != AS_public)) {
1608*67e74705SXin Li // The Microsoft extension __interface does not permit bases that
1609*67e74705SXin Li // are not themselves public interfaces.
1610*67e74705SXin Li Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611*67e74705SXin Li << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612*67e74705SXin Li << RD->getSourceRange();
1613*67e74705SXin Li Invalid = true;
1614*67e74705SXin Li }
1615*67e74705SXin Li if (RD->hasAttr<WeakAttr>())
1616*67e74705SXin Li Class->addAttr(WeakAttr::CreateImplicit(Context));
1617*67e74705SXin Li }
1618*67e74705SXin Li }
1619*67e74705SXin Li }
1620*67e74705SXin Li
1621*67e74705SXin Li // Attach the remaining base class specifiers to the derived class.
1622*67e74705SXin Li Class->setBases(Bases.data(), NumGoodBases);
1623*67e74705SXin Li
1624*67e74705SXin Li for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625*67e74705SXin Li // Check whether this direct base is inaccessible due to ambiguity.
1626*67e74705SXin Li QualType BaseType = Bases[idx]->getType();
1627*67e74705SXin Li CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628*67e74705SXin Li .getUnqualifiedType();
1629*67e74705SXin Li
1630*67e74705SXin Li if (IndirectBaseTypes.count(CanonicalBase)) {
1631*67e74705SXin Li CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632*67e74705SXin Li /*DetectVirtual=*/true);
1633*67e74705SXin Li bool found
1634*67e74705SXin Li = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1635*67e74705SXin Li assert(found);
1636*67e74705SXin Li (void)found;
1637*67e74705SXin Li
1638*67e74705SXin Li if (Paths.isAmbiguous(CanonicalBase))
1639*67e74705SXin Li Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640*67e74705SXin Li << BaseType << getAmbiguousPathsDisplayString(Paths)
1641*67e74705SXin Li << Bases[idx]->getSourceRange();
1642*67e74705SXin Li else
1643*67e74705SXin Li assert(Bases[idx]->isVirtual());
1644*67e74705SXin Li }
1645*67e74705SXin Li
1646*67e74705SXin Li // Delete the base class specifier, since its data has been copied
1647*67e74705SXin Li // into the CXXRecordDecl.
1648*67e74705SXin Li Context.Deallocate(Bases[idx]);
1649*67e74705SXin Li }
1650*67e74705SXin Li
1651*67e74705SXin Li return Invalid;
1652*67e74705SXin Li }
1653*67e74705SXin Li
1654*67e74705SXin Li /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655*67e74705SXin Li /// class, after checking whether there are any duplicate base
1656*67e74705SXin Li /// classes.
ActOnBaseSpecifiers(Decl * ClassDecl,MutableArrayRef<CXXBaseSpecifier * > Bases)1657*67e74705SXin Li void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
1658*67e74705SXin Li MutableArrayRef<CXXBaseSpecifier *> Bases) {
1659*67e74705SXin Li if (!ClassDecl || Bases.empty())
1660*67e74705SXin Li return;
1661*67e74705SXin Li
1662*67e74705SXin Li AdjustDeclIfTemplate(ClassDecl);
1663*67e74705SXin Li AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
1664*67e74705SXin Li }
1665*67e74705SXin Li
1666*67e74705SXin Li /// \brief Determine whether the type \p Derived is a C++ class that is
1667*67e74705SXin Li /// derived from the type \p Base.
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base)1668*67e74705SXin Li bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
1669*67e74705SXin Li if (!getLangOpts().CPlusPlus)
1670*67e74705SXin Li return false;
1671*67e74705SXin Li
1672*67e74705SXin Li CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1673*67e74705SXin Li if (!DerivedRD)
1674*67e74705SXin Li return false;
1675*67e74705SXin Li
1676*67e74705SXin Li CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1677*67e74705SXin Li if (!BaseRD)
1678*67e74705SXin Li return false;
1679*67e74705SXin Li
1680*67e74705SXin Li // If either the base or the derived type is invalid, don't try to
1681*67e74705SXin Li // check whether one is derived from the other.
1682*67e74705SXin Li if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1683*67e74705SXin Li return false;
1684*67e74705SXin Li
1685*67e74705SXin Li // FIXME: In a modules build, do we need the entire path to be visible for us
1686*67e74705SXin Li // to be able to use the inheritance relationship?
1687*67e74705SXin Li if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1688*67e74705SXin Li return false;
1689*67e74705SXin Li
1690*67e74705SXin Li return DerivedRD->isDerivedFrom(BaseRD);
1691*67e74705SXin Li }
1692*67e74705SXin Li
1693*67e74705SXin Li /// \brief Determine whether the type \p Derived is a C++ class that is
1694*67e74705SXin Li /// derived from the type \p Base.
IsDerivedFrom(SourceLocation Loc,QualType Derived,QualType Base,CXXBasePaths & Paths)1695*67e74705SXin Li bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
1696*67e74705SXin Li CXXBasePaths &Paths) {
1697*67e74705SXin Li if (!getLangOpts().CPlusPlus)
1698*67e74705SXin Li return false;
1699*67e74705SXin Li
1700*67e74705SXin Li CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1701*67e74705SXin Li if (!DerivedRD)
1702*67e74705SXin Li return false;
1703*67e74705SXin Li
1704*67e74705SXin Li CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1705*67e74705SXin Li if (!BaseRD)
1706*67e74705SXin Li return false;
1707*67e74705SXin Li
1708*67e74705SXin Li if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1709*67e74705SXin Li return false;
1710*67e74705SXin Li
1711*67e74705SXin Li return DerivedRD->isDerivedFrom(BaseRD, Paths);
1712*67e74705SXin Li }
1713*67e74705SXin Li
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)1714*67e74705SXin Li void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1715*67e74705SXin Li CXXCastPath &BasePathArray) {
1716*67e74705SXin Li assert(BasePathArray.empty() && "Base path array must be empty!");
1717*67e74705SXin Li assert(Paths.isRecordingPaths() && "Must record paths!");
1718*67e74705SXin Li
1719*67e74705SXin Li const CXXBasePath &Path = Paths.front();
1720*67e74705SXin Li
1721*67e74705SXin Li // We first go backward and check if we have a virtual base.
1722*67e74705SXin Li // FIXME: It would be better if CXXBasePath had the base specifier for
1723*67e74705SXin Li // the nearest virtual base.
1724*67e74705SXin Li unsigned Start = 0;
1725*67e74705SXin Li for (unsigned I = Path.size(); I != 0; --I) {
1726*67e74705SXin Li if (Path[I - 1].Base->isVirtual()) {
1727*67e74705SXin Li Start = I - 1;
1728*67e74705SXin Li break;
1729*67e74705SXin Li }
1730*67e74705SXin Li }
1731*67e74705SXin Li
1732*67e74705SXin Li // Now add all bases.
1733*67e74705SXin Li for (unsigned I = Start, E = Path.size(); I != E; ++I)
1734*67e74705SXin Li BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1735*67e74705SXin Li }
1736*67e74705SXin Li
1737*67e74705SXin Li /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1738*67e74705SXin Li /// conversion (where Derived and Base are class types) is
1739*67e74705SXin Li /// well-formed, meaning that the conversion is unambiguous (and
1740*67e74705SXin Li /// that all of the base classes are accessible). Returns true
1741*67e74705SXin Li /// and emits a diagnostic if the code is ill-formed, returns false
1742*67e74705SXin Li /// otherwise. Loc is the location where this routine should point to
1743*67e74705SXin Li /// if there is an error, and Range is the source range to highlight
1744*67e74705SXin Li /// if there is an error.
1745*67e74705SXin Li ///
1746*67e74705SXin Li /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
1747*67e74705SXin Li /// diagnostic for the respective type of error will be suppressed, but the
1748*67e74705SXin Li /// check for ill-formed code will still be performed.
1749*67e74705SXin Li bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbigiousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath,bool IgnoreAccess)1750*67e74705SXin Li Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1751*67e74705SXin Li unsigned InaccessibleBaseID,
1752*67e74705SXin Li unsigned AmbigiousBaseConvID,
1753*67e74705SXin Li SourceLocation Loc, SourceRange Range,
1754*67e74705SXin Li DeclarationName Name,
1755*67e74705SXin Li CXXCastPath *BasePath,
1756*67e74705SXin Li bool IgnoreAccess) {
1757*67e74705SXin Li // First, determine whether the path from Derived to Base is
1758*67e74705SXin Li // ambiguous. This is slightly more expensive than checking whether
1759*67e74705SXin Li // the Derived to Base conversion exists, because here we need to
1760*67e74705SXin Li // explore multiple paths to determine if there is an ambiguity.
1761*67e74705SXin Li CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1762*67e74705SXin Li /*DetectVirtual=*/false);
1763*67e74705SXin Li bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1764*67e74705SXin Li assert(DerivationOkay &&
1765*67e74705SXin Li "Can only be used with a derived-to-base conversion");
1766*67e74705SXin Li (void)DerivationOkay;
1767*67e74705SXin Li
1768*67e74705SXin Li if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1769*67e74705SXin Li if (!IgnoreAccess) {
1770*67e74705SXin Li // Check that the base class can be accessed.
1771*67e74705SXin Li switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1772*67e74705SXin Li InaccessibleBaseID)) {
1773*67e74705SXin Li case AR_inaccessible:
1774*67e74705SXin Li return true;
1775*67e74705SXin Li case AR_accessible:
1776*67e74705SXin Li case AR_dependent:
1777*67e74705SXin Li case AR_delayed:
1778*67e74705SXin Li break;
1779*67e74705SXin Li }
1780*67e74705SXin Li }
1781*67e74705SXin Li
1782*67e74705SXin Li // Build a base path if necessary.
1783*67e74705SXin Li if (BasePath)
1784*67e74705SXin Li BuildBasePathArray(Paths, *BasePath);
1785*67e74705SXin Li return false;
1786*67e74705SXin Li }
1787*67e74705SXin Li
1788*67e74705SXin Li if (AmbigiousBaseConvID) {
1789*67e74705SXin Li // We know that the derived-to-base conversion is ambiguous, and
1790*67e74705SXin Li // we're going to produce a diagnostic. Perform the derived-to-base
1791*67e74705SXin Li // search just one more time to compute all of the possible paths so
1792*67e74705SXin Li // that we can print them out. This is more expensive than any of
1793*67e74705SXin Li // the previous derived-to-base checks we've done, but at this point
1794*67e74705SXin Li // performance isn't as much of an issue.
1795*67e74705SXin Li Paths.clear();
1796*67e74705SXin Li Paths.setRecordingPaths(true);
1797*67e74705SXin Li bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1798*67e74705SXin Li assert(StillOkay && "Can only be used with a derived-to-base conversion");
1799*67e74705SXin Li (void)StillOkay;
1800*67e74705SXin Li
1801*67e74705SXin Li // Build up a textual representation of the ambiguous paths, e.g.,
1802*67e74705SXin Li // D -> B -> A, that will be used to illustrate the ambiguous
1803*67e74705SXin Li // conversions in the diagnostic. We only print one of the paths
1804*67e74705SXin Li // to each base class subobject.
1805*67e74705SXin Li std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1806*67e74705SXin Li
1807*67e74705SXin Li Diag(Loc, AmbigiousBaseConvID)
1808*67e74705SXin Li << Derived << Base << PathDisplayStr << Range << Name;
1809*67e74705SXin Li }
1810*67e74705SXin Li return true;
1811*67e74705SXin Li }
1812*67e74705SXin Li
1813*67e74705SXin Li bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)1814*67e74705SXin Li Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1815*67e74705SXin Li SourceLocation Loc, SourceRange Range,
1816*67e74705SXin Li CXXCastPath *BasePath,
1817*67e74705SXin Li bool IgnoreAccess) {
1818*67e74705SXin Li return CheckDerivedToBaseConversion(
1819*67e74705SXin Li Derived, Base, diag::err_upcast_to_inaccessible_base,
1820*67e74705SXin Li diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
1821*67e74705SXin Li BasePath, IgnoreAccess);
1822*67e74705SXin Li }
1823*67e74705SXin Li
1824*67e74705SXin Li
1825*67e74705SXin Li /// @brief Builds a string representing ambiguous paths from a
1826*67e74705SXin Li /// specific derived class to different subobjects of the same base
1827*67e74705SXin Li /// class.
1828*67e74705SXin Li ///
1829*67e74705SXin Li /// This function builds a string that can be used in error messages
1830*67e74705SXin Li /// to show the different paths that one can take through the
1831*67e74705SXin Li /// inheritance hierarchy to go from the derived class to different
1832*67e74705SXin Li /// subobjects of a base class. The result looks something like this:
1833*67e74705SXin Li /// @code
1834*67e74705SXin Li /// struct D -> struct B -> struct A
1835*67e74705SXin Li /// struct D -> struct C -> struct A
1836*67e74705SXin Li /// @endcode
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)1837*67e74705SXin Li std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1838*67e74705SXin Li std::string PathDisplayStr;
1839*67e74705SXin Li std::set<unsigned> DisplayedPaths;
1840*67e74705SXin Li for (CXXBasePaths::paths_iterator Path = Paths.begin();
1841*67e74705SXin Li Path != Paths.end(); ++Path) {
1842*67e74705SXin Li if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1843*67e74705SXin Li // We haven't displayed a path to this particular base
1844*67e74705SXin Li // class subobject yet.
1845*67e74705SXin Li PathDisplayStr += "\n ";
1846*67e74705SXin Li PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1847*67e74705SXin Li for (CXXBasePath::const_iterator Element = Path->begin();
1848*67e74705SXin Li Element != Path->end(); ++Element)
1849*67e74705SXin Li PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1850*67e74705SXin Li }
1851*67e74705SXin Li }
1852*67e74705SXin Li
1853*67e74705SXin Li return PathDisplayStr;
1854*67e74705SXin Li }
1855*67e74705SXin Li
1856*67e74705SXin Li //===----------------------------------------------------------------------===//
1857*67e74705SXin Li // C++ class member Handling
1858*67e74705SXin Li //===----------------------------------------------------------------------===//
1859*67e74705SXin Li
1860*67e74705SXin Li /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc,AttributeList * Attrs)1861*67e74705SXin Li bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1862*67e74705SXin Li SourceLocation ASLoc,
1863*67e74705SXin Li SourceLocation ColonLoc,
1864*67e74705SXin Li AttributeList *Attrs) {
1865*67e74705SXin Li assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1866*67e74705SXin Li AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1867*67e74705SXin Li ASLoc, ColonLoc);
1868*67e74705SXin Li CurContext->addHiddenDecl(ASDecl);
1869*67e74705SXin Li return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1870*67e74705SXin Li }
1871*67e74705SXin Li
1872*67e74705SXin Li /// CheckOverrideControl - Check C++11 override control semantics.
CheckOverrideControl(NamedDecl * D)1873*67e74705SXin Li void Sema::CheckOverrideControl(NamedDecl *D) {
1874*67e74705SXin Li if (D->isInvalidDecl())
1875*67e74705SXin Li return;
1876*67e74705SXin Li
1877*67e74705SXin Li // We only care about "override" and "final" declarations.
1878*67e74705SXin Li if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1879*67e74705SXin Li return;
1880*67e74705SXin Li
1881*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1882*67e74705SXin Li
1883*67e74705SXin Li // We can't check dependent instance methods.
1884*67e74705SXin Li if (MD && MD->isInstance() &&
1885*67e74705SXin Li (MD->getParent()->hasAnyDependentBases() ||
1886*67e74705SXin Li MD->getType()->isDependentType()))
1887*67e74705SXin Li return;
1888*67e74705SXin Li
1889*67e74705SXin Li if (MD && !MD->isVirtual()) {
1890*67e74705SXin Li // If we have a non-virtual method, check if if hides a virtual method.
1891*67e74705SXin Li // (In that case, it's most likely the method has the wrong type.)
1892*67e74705SXin Li SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1893*67e74705SXin Li FindHiddenVirtualMethods(MD, OverloadedMethods);
1894*67e74705SXin Li
1895*67e74705SXin Li if (!OverloadedMethods.empty()) {
1896*67e74705SXin Li if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1897*67e74705SXin Li Diag(OA->getLocation(),
1898*67e74705SXin Li diag::override_keyword_hides_virtual_member_function)
1899*67e74705SXin Li << "override" << (OverloadedMethods.size() > 1);
1900*67e74705SXin Li } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1901*67e74705SXin Li Diag(FA->getLocation(),
1902*67e74705SXin Li diag::override_keyword_hides_virtual_member_function)
1903*67e74705SXin Li << (FA->isSpelledAsSealed() ? "sealed" : "final")
1904*67e74705SXin Li << (OverloadedMethods.size() > 1);
1905*67e74705SXin Li }
1906*67e74705SXin Li NoteHiddenVirtualMethods(MD, OverloadedMethods);
1907*67e74705SXin Li MD->setInvalidDecl();
1908*67e74705SXin Li return;
1909*67e74705SXin Li }
1910*67e74705SXin Li // Fall through into the general case diagnostic.
1911*67e74705SXin Li // FIXME: We might want to attempt typo correction here.
1912*67e74705SXin Li }
1913*67e74705SXin Li
1914*67e74705SXin Li if (!MD || !MD->isVirtual()) {
1915*67e74705SXin Li if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1916*67e74705SXin Li Diag(OA->getLocation(),
1917*67e74705SXin Li diag::override_keyword_only_allowed_on_virtual_member_functions)
1918*67e74705SXin Li << "override" << FixItHint::CreateRemoval(OA->getLocation());
1919*67e74705SXin Li D->dropAttr<OverrideAttr>();
1920*67e74705SXin Li }
1921*67e74705SXin Li if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1922*67e74705SXin Li Diag(FA->getLocation(),
1923*67e74705SXin Li diag::override_keyword_only_allowed_on_virtual_member_functions)
1924*67e74705SXin Li << (FA->isSpelledAsSealed() ? "sealed" : "final")
1925*67e74705SXin Li << FixItHint::CreateRemoval(FA->getLocation());
1926*67e74705SXin Li D->dropAttr<FinalAttr>();
1927*67e74705SXin Li }
1928*67e74705SXin Li return;
1929*67e74705SXin Li }
1930*67e74705SXin Li
1931*67e74705SXin Li // C++11 [class.virtual]p5:
1932*67e74705SXin Li // If a function is marked with the virt-specifier override and
1933*67e74705SXin Li // does not override a member function of a base class, the program is
1934*67e74705SXin Li // ill-formed.
1935*67e74705SXin Li bool HasOverriddenMethods =
1936*67e74705SXin Li MD->begin_overridden_methods() != MD->end_overridden_methods();
1937*67e74705SXin Li if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1938*67e74705SXin Li Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1939*67e74705SXin Li << MD->getDeclName();
1940*67e74705SXin Li }
1941*67e74705SXin Li
DiagnoseAbsenceOfOverrideControl(NamedDecl * D)1942*67e74705SXin Li void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1943*67e74705SXin Li if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1944*67e74705SXin Li return;
1945*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1946*67e74705SXin Li if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1947*67e74705SXin Li isa<CXXDestructorDecl>(MD))
1948*67e74705SXin Li return;
1949*67e74705SXin Li
1950*67e74705SXin Li SourceLocation Loc = MD->getLocation();
1951*67e74705SXin Li SourceLocation SpellingLoc = Loc;
1952*67e74705SXin Li if (getSourceManager().isMacroArgExpansion(Loc))
1953*67e74705SXin Li SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1954*67e74705SXin Li SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1955*67e74705SXin Li if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1956*67e74705SXin Li return;
1957*67e74705SXin Li
1958*67e74705SXin Li if (MD->size_overridden_methods() > 0) {
1959*67e74705SXin Li Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1960*67e74705SXin Li << MD->getDeclName();
1961*67e74705SXin Li const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1962*67e74705SXin Li Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1963*67e74705SXin Li }
1964*67e74705SXin Li }
1965*67e74705SXin Li
1966*67e74705SXin Li /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1967*67e74705SXin Li /// function overrides a virtual member function marked 'final', according to
1968*67e74705SXin Li /// C++11 [class.virtual]p4.
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)1969*67e74705SXin Li bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1970*67e74705SXin Li const CXXMethodDecl *Old) {
1971*67e74705SXin Li FinalAttr *FA = Old->getAttr<FinalAttr>();
1972*67e74705SXin Li if (!FA)
1973*67e74705SXin Li return false;
1974*67e74705SXin Li
1975*67e74705SXin Li Diag(New->getLocation(), diag::err_final_function_overridden)
1976*67e74705SXin Li << New->getDeclName()
1977*67e74705SXin Li << FA->isSpelledAsSealed();
1978*67e74705SXin Li Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1979*67e74705SXin Li return true;
1980*67e74705SXin Li }
1981*67e74705SXin Li
InitializationHasSideEffects(const FieldDecl & FD)1982*67e74705SXin Li static bool InitializationHasSideEffects(const FieldDecl &FD) {
1983*67e74705SXin Li const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1984*67e74705SXin Li // FIXME: Destruction of ObjC lifetime types has side-effects.
1985*67e74705SXin Li if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1986*67e74705SXin Li return !RD->isCompleteDefinition() ||
1987*67e74705SXin Li !RD->hasTrivialDefaultConstructor() ||
1988*67e74705SXin Li !RD->hasTrivialDestructor();
1989*67e74705SXin Li return false;
1990*67e74705SXin Li }
1991*67e74705SXin Li
getMSPropertyAttr(AttributeList * list)1992*67e74705SXin Li static AttributeList *getMSPropertyAttr(AttributeList *list) {
1993*67e74705SXin Li for (AttributeList *it = list; it != nullptr; it = it->getNext())
1994*67e74705SXin Li if (it->isDeclspecPropertyAttribute())
1995*67e74705SXin Li return it;
1996*67e74705SXin Li return nullptr;
1997*67e74705SXin Li }
1998*67e74705SXin Li
1999*67e74705SXin Li /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2000*67e74705SXin Li /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2001*67e74705SXin Li /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2002*67e74705SXin Li /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2003*67e74705SXin Li /// present (but parsing it has been deferred).
2004*67e74705SXin Li NamedDecl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,Expr * BW,const VirtSpecifiers & VS,InClassInitStyle InitStyle)2005*67e74705SXin Li Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2006*67e74705SXin Li MultiTemplateParamsArg TemplateParameterLists,
2007*67e74705SXin Li Expr *BW, const VirtSpecifiers &VS,
2008*67e74705SXin Li InClassInitStyle InitStyle) {
2009*67e74705SXin Li const DeclSpec &DS = D.getDeclSpec();
2010*67e74705SXin Li DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2011*67e74705SXin Li DeclarationName Name = NameInfo.getName();
2012*67e74705SXin Li SourceLocation Loc = NameInfo.getLoc();
2013*67e74705SXin Li
2014*67e74705SXin Li // For anonymous bitfields, the location should point to the type.
2015*67e74705SXin Li if (Loc.isInvalid())
2016*67e74705SXin Li Loc = D.getLocStart();
2017*67e74705SXin Li
2018*67e74705SXin Li Expr *BitWidth = static_cast<Expr*>(BW);
2019*67e74705SXin Li
2020*67e74705SXin Li assert(isa<CXXRecordDecl>(CurContext));
2021*67e74705SXin Li assert(!DS.isFriendSpecified());
2022*67e74705SXin Li
2023*67e74705SXin Li bool isFunc = D.isDeclarationOfFunction();
2024*67e74705SXin Li
2025*67e74705SXin Li if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2026*67e74705SXin Li // The Microsoft extension __interface only permits public member functions
2027*67e74705SXin Li // and prohibits constructors, destructors, operators, non-public member
2028*67e74705SXin Li // functions, static methods and data members.
2029*67e74705SXin Li unsigned InvalidDecl;
2030*67e74705SXin Li bool ShowDeclName = true;
2031*67e74705SXin Li if (!isFunc)
2032*67e74705SXin Li InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2033*67e74705SXin Li else if (AS != AS_public)
2034*67e74705SXin Li InvalidDecl = 2;
2035*67e74705SXin Li else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2036*67e74705SXin Li InvalidDecl = 3;
2037*67e74705SXin Li else switch (Name.getNameKind()) {
2038*67e74705SXin Li case DeclarationName::CXXConstructorName:
2039*67e74705SXin Li InvalidDecl = 4;
2040*67e74705SXin Li ShowDeclName = false;
2041*67e74705SXin Li break;
2042*67e74705SXin Li
2043*67e74705SXin Li case DeclarationName::CXXDestructorName:
2044*67e74705SXin Li InvalidDecl = 5;
2045*67e74705SXin Li ShowDeclName = false;
2046*67e74705SXin Li break;
2047*67e74705SXin Li
2048*67e74705SXin Li case DeclarationName::CXXOperatorName:
2049*67e74705SXin Li case DeclarationName::CXXConversionFunctionName:
2050*67e74705SXin Li InvalidDecl = 6;
2051*67e74705SXin Li break;
2052*67e74705SXin Li
2053*67e74705SXin Li default:
2054*67e74705SXin Li InvalidDecl = 0;
2055*67e74705SXin Li break;
2056*67e74705SXin Li }
2057*67e74705SXin Li
2058*67e74705SXin Li if (InvalidDecl) {
2059*67e74705SXin Li if (ShowDeclName)
2060*67e74705SXin Li Diag(Loc, diag::err_invalid_member_in_interface)
2061*67e74705SXin Li << (InvalidDecl-1) << Name;
2062*67e74705SXin Li else
2063*67e74705SXin Li Diag(Loc, diag::err_invalid_member_in_interface)
2064*67e74705SXin Li << (InvalidDecl-1) << "";
2065*67e74705SXin Li return nullptr;
2066*67e74705SXin Li }
2067*67e74705SXin Li }
2068*67e74705SXin Li
2069*67e74705SXin Li // C++ 9.2p6: A member shall not be declared to have automatic storage
2070*67e74705SXin Li // duration (auto, register) or with the extern storage-class-specifier.
2071*67e74705SXin Li // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2072*67e74705SXin Li // data members and cannot be applied to names declared const or static,
2073*67e74705SXin Li // and cannot be applied to reference members.
2074*67e74705SXin Li switch (DS.getStorageClassSpec()) {
2075*67e74705SXin Li case DeclSpec::SCS_unspecified:
2076*67e74705SXin Li case DeclSpec::SCS_typedef:
2077*67e74705SXin Li case DeclSpec::SCS_static:
2078*67e74705SXin Li break;
2079*67e74705SXin Li case DeclSpec::SCS_mutable:
2080*67e74705SXin Li if (isFunc) {
2081*67e74705SXin Li Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2082*67e74705SXin Li
2083*67e74705SXin Li // FIXME: It would be nicer if the keyword was ignored only for this
2084*67e74705SXin Li // declarator. Otherwise we could get follow-up errors.
2085*67e74705SXin Li D.getMutableDeclSpec().ClearStorageClassSpecs();
2086*67e74705SXin Li }
2087*67e74705SXin Li break;
2088*67e74705SXin Li default:
2089*67e74705SXin Li Diag(DS.getStorageClassSpecLoc(),
2090*67e74705SXin Li diag::err_storageclass_invalid_for_member);
2091*67e74705SXin Li D.getMutableDeclSpec().ClearStorageClassSpecs();
2092*67e74705SXin Li break;
2093*67e74705SXin Li }
2094*67e74705SXin Li
2095*67e74705SXin Li bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2096*67e74705SXin Li DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2097*67e74705SXin Li !isFunc);
2098*67e74705SXin Li
2099*67e74705SXin Li if (DS.isConstexprSpecified() && isInstField) {
2100*67e74705SXin Li SemaDiagnosticBuilder B =
2101*67e74705SXin Li Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2102*67e74705SXin Li SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2103*67e74705SXin Li if (InitStyle == ICIS_NoInit) {
2104*67e74705SXin Li B << 0 << 0;
2105*67e74705SXin Li if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2106*67e74705SXin Li B << FixItHint::CreateRemoval(ConstexprLoc);
2107*67e74705SXin Li else {
2108*67e74705SXin Li B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2109*67e74705SXin Li D.getMutableDeclSpec().ClearConstexprSpec();
2110*67e74705SXin Li const char *PrevSpec;
2111*67e74705SXin Li unsigned DiagID;
2112*67e74705SXin Li bool Failed = D.getMutableDeclSpec().SetTypeQual(
2113*67e74705SXin Li DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2114*67e74705SXin Li (void)Failed;
2115*67e74705SXin Li assert(!Failed && "Making a constexpr member const shouldn't fail");
2116*67e74705SXin Li }
2117*67e74705SXin Li } else {
2118*67e74705SXin Li B << 1;
2119*67e74705SXin Li const char *PrevSpec;
2120*67e74705SXin Li unsigned DiagID;
2121*67e74705SXin Li if (D.getMutableDeclSpec().SetStorageClassSpec(
2122*67e74705SXin Li *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2123*67e74705SXin Li Context.getPrintingPolicy())) {
2124*67e74705SXin Li assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2125*67e74705SXin Li "This is the only DeclSpec that should fail to be applied");
2126*67e74705SXin Li B << 1;
2127*67e74705SXin Li } else {
2128*67e74705SXin Li B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2129*67e74705SXin Li isInstField = false;
2130*67e74705SXin Li }
2131*67e74705SXin Li }
2132*67e74705SXin Li }
2133*67e74705SXin Li
2134*67e74705SXin Li NamedDecl *Member;
2135*67e74705SXin Li if (isInstField) {
2136*67e74705SXin Li CXXScopeSpec &SS = D.getCXXScopeSpec();
2137*67e74705SXin Li
2138*67e74705SXin Li // Data members must have identifiers for names.
2139*67e74705SXin Li if (!Name.isIdentifier()) {
2140*67e74705SXin Li Diag(Loc, diag::err_bad_variable_name)
2141*67e74705SXin Li << Name;
2142*67e74705SXin Li return nullptr;
2143*67e74705SXin Li }
2144*67e74705SXin Li
2145*67e74705SXin Li IdentifierInfo *II = Name.getAsIdentifierInfo();
2146*67e74705SXin Li
2147*67e74705SXin Li // Member field could not be with "template" keyword.
2148*67e74705SXin Li // So TemplateParameterLists should be empty in this case.
2149*67e74705SXin Li if (TemplateParameterLists.size()) {
2150*67e74705SXin Li TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2151*67e74705SXin Li if (TemplateParams->size()) {
2152*67e74705SXin Li // There is no such thing as a member field template.
2153*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_template_member)
2154*67e74705SXin Li << II
2155*67e74705SXin Li << SourceRange(TemplateParams->getTemplateLoc(),
2156*67e74705SXin Li TemplateParams->getRAngleLoc());
2157*67e74705SXin Li } else {
2158*67e74705SXin Li // There is an extraneous 'template<>' for this member.
2159*67e74705SXin Li Diag(TemplateParams->getTemplateLoc(),
2160*67e74705SXin Li diag::err_template_member_noparams)
2161*67e74705SXin Li << II
2162*67e74705SXin Li << SourceRange(TemplateParams->getTemplateLoc(),
2163*67e74705SXin Li TemplateParams->getRAngleLoc());
2164*67e74705SXin Li }
2165*67e74705SXin Li return nullptr;
2166*67e74705SXin Li }
2167*67e74705SXin Li
2168*67e74705SXin Li if (SS.isSet() && !SS.isInvalid()) {
2169*67e74705SXin Li // The user provided a superfluous scope specifier inside a class
2170*67e74705SXin Li // definition:
2171*67e74705SXin Li //
2172*67e74705SXin Li // class X {
2173*67e74705SXin Li // int X::member;
2174*67e74705SXin Li // };
2175*67e74705SXin Li if (DeclContext *DC = computeDeclContext(SS, false))
2176*67e74705SXin Li diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2177*67e74705SXin Li else
2178*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2179*67e74705SXin Li << Name << SS.getRange();
2180*67e74705SXin Li
2181*67e74705SXin Li SS.clear();
2182*67e74705SXin Li }
2183*67e74705SXin Li
2184*67e74705SXin Li AttributeList *MSPropertyAttr =
2185*67e74705SXin Li getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2186*67e74705SXin Li if (MSPropertyAttr) {
2187*67e74705SXin Li Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2188*67e74705SXin Li BitWidth, InitStyle, AS, MSPropertyAttr);
2189*67e74705SXin Li if (!Member)
2190*67e74705SXin Li return nullptr;
2191*67e74705SXin Li isInstField = false;
2192*67e74705SXin Li } else {
2193*67e74705SXin Li Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2194*67e74705SXin Li BitWidth, InitStyle, AS);
2195*67e74705SXin Li assert(Member && "HandleField never returns null");
2196*67e74705SXin Li }
2197*67e74705SXin Li } else {
2198*67e74705SXin Li Member = HandleDeclarator(S, D, TemplateParameterLists);
2199*67e74705SXin Li if (!Member)
2200*67e74705SXin Li return nullptr;
2201*67e74705SXin Li
2202*67e74705SXin Li // Non-instance-fields can't have a bitfield.
2203*67e74705SXin Li if (BitWidth) {
2204*67e74705SXin Li if (Member->isInvalidDecl()) {
2205*67e74705SXin Li // don't emit another diagnostic.
2206*67e74705SXin Li } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2207*67e74705SXin Li // C++ 9.6p3: A bit-field shall not be a static member.
2208*67e74705SXin Li // "static member 'A' cannot be a bit-field"
2209*67e74705SXin Li Diag(Loc, diag::err_static_not_bitfield)
2210*67e74705SXin Li << Name << BitWidth->getSourceRange();
2211*67e74705SXin Li } else if (isa<TypedefDecl>(Member)) {
2212*67e74705SXin Li // "typedef member 'x' cannot be a bit-field"
2213*67e74705SXin Li Diag(Loc, diag::err_typedef_not_bitfield)
2214*67e74705SXin Li << Name << BitWidth->getSourceRange();
2215*67e74705SXin Li } else {
2216*67e74705SXin Li // A function typedef ("typedef int f(); f a;").
2217*67e74705SXin Li // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2218*67e74705SXin Li Diag(Loc, diag::err_not_integral_type_bitfield)
2219*67e74705SXin Li << Name << cast<ValueDecl>(Member)->getType()
2220*67e74705SXin Li << BitWidth->getSourceRange();
2221*67e74705SXin Li }
2222*67e74705SXin Li
2223*67e74705SXin Li BitWidth = nullptr;
2224*67e74705SXin Li Member->setInvalidDecl();
2225*67e74705SXin Li }
2226*67e74705SXin Li
2227*67e74705SXin Li Member->setAccess(AS);
2228*67e74705SXin Li
2229*67e74705SXin Li // If we have declared a member function template or static data member
2230*67e74705SXin Li // template, set the access of the templated declaration as well.
2231*67e74705SXin Li if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2232*67e74705SXin Li FunTmpl->getTemplatedDecl()->setAccess(AS);
2233*67e74705SXin Li else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2234*67e74705SXin Li VarTmpl->getTemplatedDecl()->setAccess(AS);
2235*67e74705SXin Li }
2236*67e74705SXin Li
2237*67e74705SXin Li if (VS.isOverrideSpecified())
2238*67e74705SXin Li Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2239*67e74705SXin Li if (VS.isFinalSpecified())
2240*67e74705SXin Li Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2241*67e74705SXin Li VS.isFinalSpelledSealed()));
2242*67e74705SXin Li
2243*67e74705SXin Li if (VS.getLastLocation().isValid()) {
2244*67e74705SXin Li // Update the end location of a method that has a virt-specifiers.
2245*67e74705SXin Li if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2246*67e74705SXin Li MD->setRangeEnd(VS.getLastLocation());
2247*67e74705SXin Li }
2248*67e74705SXin Li
2249*67e74705SXin Li CheckOverrideControl(Member);
2250*67e74705SXin Li
2251*67e74705SXin Li assert((Name || isInstField) && "No identifier for non-field ?");
2252*67e74705SXin Li
2253*67e74705SXin Li if (isInstField) {
2254*67e74705SXin Li FieldDecl *FD = cast<FieldDecl>(Member);
2255*67e74705SXin Li FieldCollector->Add(FD);
2256*67e74705SXin Li
2257*67e74705SXin Li if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2258*67e74705SXin Li // Remember all explicit private FieldDecls that have a name, no side
2259*67e74705SXin Li // effects and are not part of a dependent type declaration.
2260*67e74705SXin Li if (!FD->isImplicit() && FD->getDeclName() &&
2261*67e74705SXin Li FD->getAccess() == AS_private &&
2262*67e74705SXin Li !FD->hasAttr<UnusedAttr>() &&
2263*67e74705SXin Li !FD->getParent()->isDependentContext() &&
2264*67e74705SXin Li !InitializationHasSideEffects(*FD))
2265*67e74705SXin Li UnusedPrivateFields.insert(FD);
2266*67e74705SXin Li }
2267*67e74705SXin Li }
2268*67e74705SXin Li
2269*67e74705SXin Li return Member;
2270*67e74705SXin Li }
2271*67e74705SXin Li
2272*67e74705SXin Li namespace {
2273*67e74705SXin Li class UninitializedFieldVisitor
2274*67e74705SXin Li : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2275*67e74705SXin Li Sema &S;
2276*67e74705SXin Li // List of Decls to generate a warning on. Also remove Decls that become
2277*67e74705SXin Li // initialized.
2278*67e74705SXin Li llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2279*67e74705SXin Li // List of base classes of the record. Classes are removed after their
2280*67e74705SXin Li // initializers.
2281*67e74705SXin Li llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2282*67e74705SXin Li // Vector of decls to be removed from the Decl set prior to visiting the
2283*67e74705SXin Li // nodes. These Decls may have been initialized in the prior initializer.
2284*67e74705SXin Li llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2285*67e74705SXin Li // If non-null, add a note to the warning pointing back to the constructor.
2286*67e74705SXin Li const CXXConstructorDecl *Constructor;
2287*67e74705SXin Li // Variables to hold state when processing an initializer list. When
2288*67e74705SXin Li // InitList is true, special case initialization of FieldDecls matching
2289*67e74705SXin Li // InitListFieldDecl.
2290*67e74705SXin Li bool InitList;
2291*67e74705SXin Li FieldDecl *InitListFieldDecl;
2292*67e74705SXin Li llvm::SmallVector<unsigned, 4> InitFieldIndex;
2293*67e74705SXin Li
2294*67e74705SXin Li public:
2295*67e74705SXin Li typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
UninitializedFieldVisitor(Sema & S,llvm::SmallPtrSetImpl<ValueDecl * > & Decls,llvm::SmallPtrSetImpl<QualType> & BaseClasses)2296*67e74705SXin Li UninitializedFieldVisitor(Sema &S,
2297*67e74705SXin Li llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2298*67e74705SXin Li llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2299*67e74705SXin Li : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2300*67e74705SXin Li Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2301*67e74705SXin Li
2302*67e74705SXin Li // Returns true if the use of ME is not an uninitialized use.
IsInitListMemberExprInitialized(MemberExpr * ME,bool CheckReferenceOnly)2303*67e74705SXin Li bool IsInitListMemberExprInitialized(MemberExpr *ME,
2304*67e74705SXin Li bool CheckReferenceOnly) {
2305*67e74705SXin Li llvm::SmallVector<FieldDecl*, 4> Fields;
2306*67e74705SXin Li bool ReferenceField = false;
2307*67e74705SXin Li while (ME) {
2308*67e74705SXin Li FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2309*67e74705SXin Li if (!FD)
2310*67e74705SXin Li return false;
2311*67e74705SXin Li Fields.push_back(FD);
2312*67e74705SXin Li if (FD->getType()->isReferenceType())
2313*67e74705SXin Li ReferenceField = true;
2314*67e74705SXin Li ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2315*67e74705SXin Li }
2316*67e74705SXin Li
2317*67e74705SXin Li // Binding a reference to an unintialized field is not an
2318*67e74705SXin Li // uninitialized use.
2319*67e74705SXin Li if (CheckReferenceOnly && !ReferenceField)
2320*67e74705SXin Li return true;
2321*67e74705SXin Li
2322*67e74705SXin Li llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2323*67e74705SXin Li // Discard the first field since it is the field decl that is being
2324*67e74705SXin Li // initialized.
2325*67e74705SXin Li for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2326*67e74705SXin Li UsedFieldIndex.push_back((*I)->getFieldIndex());
2327*67e74705SXin Li }
2328*67e74705SXin Li
2329*67e74705SXin Li for (auto UsedIter = UsedFieldIndex.begin(),
2330*67e74705SXin Li UsedEnd = UsedFieldIndex.end(),
2331*67e74705SXin Li OrigIter = InitFieldIndex.begin(),
2332*67e74705SXin Li OrigEnd = InitFieldIndex.end();
2333*67e74705SXin Li UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2334*67e74705SXin Li if (*UsedIter < *OrigIter)
2335*67e74705SXin Li return true;
2336*67e74705SXin Li if (*UsedIter > *OrigIter)
2337*67e74705SXin Li break;
2338*67e74705SXin Li }
2339*67e74705SXin Li
2340*67e74705SXin Li return false;
2341*67e74705SXin Li }
2342*67e74705SXin Li
HandleMemberExpr(MemberExpr * ME,bool CheckReferenceOnly,bool AddressOf)2343*67e74705SXin Li void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2344*67e74705SXin Li bool AddressOf) {
2345*67e74705SXin Li if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2346*67e74705SXin Li return;
2347*67e74705SXin Li
2348*67e74705SXin Li // FieldME is the inner-most MemberExpr that is not an anonymous struct
2349*67e74705SXin Li // or union.
2350*67e74705SXin Li MemberExpr *FieldME = ME;
2351*67e74705SXin Li
2352*67e74705SXin Li bool AllPODFields = FieldME->getType().isPODType(S.Context);
2353*67e74705SXin Li
2354*67e74705SXin Li Expr *Base = ME;
2355*67e74705SXin Li while (MemberExpr *SubME =
2356*67e74705SXin Li dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2357*67e74705SXin Li
2358*67e74705SXin Li if (isa<VarDecl>(SubME->getMemberDecl()))
2359*67e74705SXin Li return;
2360*67e74705SXin Li
2361*67e74705SXin Li if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2362*67e74705SXin Li if (!FD->isAnonymousStructOrUnion())
2363*67e74705SXin Li FieldME = SubME;
2364*67e74705SXin Li
2365*67e74705SXin Li if (!FieldME->getType().isPODType(S.Context))
2366*67e74705SXin Li AllPODFields = false;
2367*67e74705SXin Li
2368*67e74705SXin Li Base = SubME->getBase();
2369*67e74705SXin Li }
2370*67e74705SXin Li
2371*67e74705SXin Li if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2372*67e74705SXin Li return;
2373*67e74705SXin Li
2374*67e74705SXin Li if (AddressOf && AllPODFields)
2375*67e74705SXin Li return;
2376*67e74705SXin Li
2377*67e74705SXin Li ValueDecl* FoundVD = FieldME->getMemberDecl();
2378*67e74705SXin Li
2379*67e74705SXin Li if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2380*67e74705SXin Li while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2381*67e74705SXin Li BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2382*67e74705SXin Li }
2383*67e74705SXin Li
2384*67e74705SXin Li if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2385*67e74705SXin Li QualType T = BaseCast->getType();
2386*67e74705SXin Li if (T->isPointerType() &&
2387*67e74705SXin Li BaseClasses.count(T->getPointeeType())) {
2388*67e74705SXin Li S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2389*67e74705SXin Li << T->getPointeeType() << FoundVD;
2390*67e74705SXin Li }
2391*67e74705SXin Li }
2392*67e74705SXin Li }
2393*67e74705SXin Li
2394*67e74705SXin Li if (!Decls.count(FoundVD))
2395*67e74705SXin Li return;
2396*67e74705SXin Li
2397*67e74705SXin Li const bool IsReference = FoundVD->getType()->isReferenceType();
2398*67e74705SXin Li
2399*67e74705SXin Li if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2400*67e74705SXin Li // Special checking for initializer lists.
2401*67e74705SXin Li if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2402*67e74705SXin Li return;
2403*67e74705SXin Li }
2404*67e74705SXin Li } else {
2405*67e74705SXin Li // Prevent double warnings on use of unbounded references.
2406*67e74705SXin Li if (CheckReferenceOnly && !IsReference)
2407*67e74705SXin Li return;
2408*67e74705SXin Li }
2409*67e74705SXin Li
2410*67e74705SXin Li unsigned diag = IsReference
2411*67e74705SXin Li ? diag::warn_reference_field_is_uninit
2412*67e74705SXin Li : diag::warn_field_is_uninit;
2413*67e74705SXin Li S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2414*67e74705SXin Li if (Constructor)
2415*67e74705SXin Li S.Diag(Constructor->getLocation(),
2416*67e74705SXin Li diag::note_uninit_in_this_constructor)
2417*67e74705SXin Li << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2418*67e74705SXin Li
2419*67e74705SXin Li }
2420*67e74705SXin Li
HandleValue(Expr * E,bool AddressOf)2421*67e74705SXin Li void HandleValue(Expr *E, bool AddressOf) {
2422*67e74705SXin Li E = E->IgnoreParens();
2423*67e74705SXin Li
2424*67e74705SXin Li if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2425*67e74705SXin Li HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2426*67e74705SXin Li AddressOf /*AddressOf*/);
2427*67e74705SXin Li return;
2428*67e74705SXin Li }
2429*67e74705SXin Li
2430*67e74705SXin Li if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2431*67e74705SXin Li Visit(CO->getCond());
2432*67e74705SXin Li HandleValue(CO->getTrueExpr(), AddressOf);
2433*67e74705SXin Li HandleValue(CO->getFalseExpr(), AddressOf);
2434*67e74705SXin Li return;
2435*67e74705SXin Li }
2436*67e74705SXin Li
2437*67e74705SXin Li if (BinaryConditionalOperator *BCO =
2438*67e74705SXin Li dyn_cast<BinaryConditionalOperator>(E)) {
2439*67e74705SXin Li Visit(BCO->getCond());
2440*67e74705SXin Li HandleValue(BCO->getFalseExpr(), AddressOf);
2441*67e74705SXin Li return;
2442*67e74705SXin Li }
2443*67e74705SXin Li
2444*67e74705SXin Li if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2445*67e74705SXin Li HandleValue(OVE->getSourceExpr(), AddressOf);
2446*67e74705SXin Li return;
2447*67e74705SXin Li }
2448*67e74705SXin Li
2449*67e74705SXin Li if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2450*67e74705SXin Li switch (BO->getOpcode()) {
2451*67e74705SXin Li default:
2452*67e74705SXin Li break;
2453*67e74705SXin Li case(BO_PtrMemD):
2454*67e74705SXin Li case(BO_PtrMemI):
2455*67e74705SXin Li HandleValue(BO->getLHS(), AddressOf);
2456*67e74705SXin Li Visit(BO->getRHS());
2457*67e74705SXin Li return;
2458*67e74705SXin Li case(BO_Comma):
2459*67e74705SXin Li Visit(BO->getLHS());
2460*67e74705SXin Li HandleValue(BO->getRHS(), AddressOf);
2461*67e74705SXin Li return;
2462*67e74705SXin Li }
2463*67e74705SXin Li }
2464*67e74705SXin Li
2465*67e74705SXin Li Visit(E);
2466*67e74705SXin Li }
2467*67e74705SXin Li
CheckInitListExpr(InitListExpr * ILE)2468*67e74705SXin Li void CheckInitListExpr(InitListExpr *ILE) {
2469*67e74705SXin Li InitFieldIndex.push_back(0);
2470*67e74705SXin Li for (auto Child : ILE->children()) {
2471*67e74705SXin Li if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2472*67e74705SXin Li CheckInitListExpr(SubList);
2473*67e74705SXin Li } else {
2474*67e74705SXin Li Visit(Child);
2475*67e74705SXin Li }
2476*67e74705SXin Li ++InitFieldIndex.back();
2477*67e74705SXin Li }
2478*67e74705SXin Li InitFieldIndex.pop_back();
2479*67e74705SXin Li }
2480*67e74705SXin Li
CheckInitializer(Expr * E,const CXXConstructorDecl * FieldConstructor,FieldDecl * Field,const Type * BaseClass)2481*67e74705SXin Li void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2482*67e74705SXin Li FieldDecl *Field, const Type *BaseClass) {
2483*67e74705SXin Li // Remove Decls that may have been initialized in the previous
2484*67e74705SXin Li // initializer.
2485*67e74705SXin Li for (ValueDecl* VD : DeclsToRemove)
2486*67e74705SXin Li Decls.erase(VD);
2487*67e74705SXin Li DeclsToRemove.clear();
2488*67e74705SXin Li
2489*67e74705SXin Li Constructor = FieldConstructor;
2490*67e74705SXin Li InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2491*67e74705SXin Li
2492*67e74705SXin Li if (ILE && Field) {
2493*67e74705SXin Li InitList = true;
2494*67e74705SXin Li InitListFieldDecl = Field;
2495*67e74705SXin Li InitFieldIndex.clear();
2496*67e74705SXin Li CheckInitListExpr(ILE);
2497*67e74705SXin Li } else {
2498*67e74705SXin Li InitList = false;
2499*67e74705SXin Li Visit(E);
2500*67e74705SXin Li }
2501*67e74705SXin Li
2502*67e74705SXin Li if (Field)
2503*67e74705SXin Li Decls.erase(Field);
2504*67e74705SXin Li if (BaseClass)
2505*67e74705SXin Li BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2506*67e74705SXin Li }
2507*67e74705SXin Li
VisitMemberExpr(MemberExpr * ME)2508*67e74705SXin Li void VisitMemberExpr(MemberExpr *ME) {
2509*67e74705SXin Li // All uses of unbounded reference fields will warn.
2510*67e74705SXin Li HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2511*67e74705SXin Li }
2512*67e74705SXin Li
VisitImplicitCastExpr(ImplicitCastExpr * E)2513*67e74705SXin Li void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2514*67e74705SXin Li if (E->getCastKind() == CK_LValueToRValue) {
2515*67e74705SXin Li HandleValue(E->getSubExpr(), false /*AddressOf*/);
2516*67e74705SXin Li return;
2517*67e74705SXin Li }
2518*67e74705SXin Li
2519*67e74705SXin Li Inherited::VisitImplicitCastExpr(E);
2520*67e74705SXin Li }
2521*67e74705SXin Li
VisitCXXConstructExpr(CXXConstructExpr * E)2522*67e74705SXin Li void VisitCXXConstructExpr(CXXConstructExpr *E) {
2523*67e74705SXin Li if (E->getConstructor()->isCopyConstructor()) {
2524*67e74705SXin Li Expr *ArgExpr = E->getArg(0);
2525*67e74705SXin Li if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2526*67e74705SXin Li if (ILE->getNumInits() == 1)
2527*67e74705SXin Li ArgExpr = ILE->getInit(0);
2528*67e74705SXin Li if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2529*67e74705SXin Li if (ICE->getCastKind() == CK_NoOp)
2530*67e74705SXin Li ArgExpr = ICE->getSubExpr();
2531*67e74705SXin Li HandleValue(ArgExpr, false /*AddressOf*/);
2532*67e74705SXin Li return;
2533*67e74705SXin Li }
2534*67e74705SXin Li Inherited::VisitCXXConstructExpr(E);
2535*67e74705SXin Li }
2536*67e74705SXin Li
VisitCXXMemberCallExpr(CXXMemberCallExpr * E)2537*67e74705SXin Li void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2538*67e74705SXin Li Expr *Callee = E->getCallee();
2539*67e74705SXin Li if (isa<MemberExpr>(Callee)) {
2540*67e74705SXin Li HandleValue(Callee, false /*AddressOf*/);
2541*67e74705SXin Li for (auto Arg : E->arguments())
2542*67e74705SXin Li Visit(Arg);
2543*67e74705SXin Li return;
2544*67e74705SXin Li }
2545*67e74705SXin Li
2546*67e74705SXin Li Inherited::VisitCXXMemberCallExpr(E);
2547*67e74705SXin Li }
2548*67e74705SXin Li
VisitCallExpr(CallExpr * E)2549*67e74705SXin Li void VisitCallExpr(CallExpr *E) {
2550*67e74705SXin Li // Treat std::move as a use.
2551*67e74705SXin Li if (E->getNumArgs() == 1) {
2552*67e74705SXin Li if (FunctionDecl *FD = E->getDirectCallee()) {
2553*67e74705SXin Li if (FD->isInStdNamespace() && FD->getIdentifier() &&
2554*67e74705SXin Li FD->getIdentifier()->isStr("move")) {
2555*67e74705SXin Li HandleValue(E->getArg(0), false /*AddressOf*/);
2556*67e74705SXin Li return;
2557*67e74705SXin Li }
2558*67e74705SXin Li }
2559*67e74705SXin Li }
2560*67e74705SXin Li
2561*67e74705SXin Li Inherited::VisitCallExpr(E);
2562*67e74705SXin Li }
2563*67e74705SXin Li
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)2564*67e74705SXin Li void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2565*67e74705SXin Li Expr *Callee = E->getCallee();
2566*67e74705SXin Li
2567*67e74705SXin Li if (isa<UnresolvedLookupExpr>(Callee))
2568*67e74705SXin Li return Inherited::VisitCXXOperatorCallExpr(E);
2569*67e74705SXin Li
2570*67e74705SXin Li Visit(Callee);
2571*67e74705SXin Li for (auto Arg : E->arguments())
2572*67e74705SXin Li HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2573*67e74705SXin Li }
2574*67e74705SXin Li
VisitBinaryOperator(BinaryOperator * E)2575*67e74705SXin Li void VisitBinaryOperator(BinaryOperator *E) {
2576*67e74705SXin Li // If a field assignment is detected, remove the field from the
2577*67e74705SXin Li // uninitiailized field set.
2578*67e74705SXin Li if (E->getOpcode() == BO_Assign)
2579*67e74705SXin Li if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2580*67e74705SXin Li if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2581*67e74705SXin Li if (!FD->getType()->isReferenceType())
2582*67e74705SXin Li DeclsToRemove.push_back(FD);
2583*67e74705SXin Li
2584*67e74705SXin Li if (E->isCompoundAssignmentOp()) {
2585*67e74705SXin Li HandleValue(E->getLHS(), false /*AddressOf*/);
2586*67e74705SXin Li Visit(E->getRHS());
2587*67e74705SXin Li return;
2588*67e74705SXin Li }
2589*67e74705SXin Li
2590*67e74705SXin Li Inherited::VisitBinaryOperator(E);
2591*67e74705SXin Li }
2592*67e74705SXin Li
VisitUnaryOperator(UnaryOperator * E)2593*67e74705SXin Li void VisitUnaryOperator(UnaryOperator *E) {
2594*67e74705SXin Li if (E->isIncrementDecrementOp()) {
2595*67e74705SXin Li HandleValue(E->getSubExpr(), false /*AddressOf*/);
2596*67e74705SXin Li return;
2597*67e74705SXin Li }
2598*67e74705SXin Li if (E->getOpcode() == UO_AddrOf) {
2599*67e74705SXin Li if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2600*67e74705SXin Li HandleValue(ME->getBase(), true /*AddressOf*/);
2601*67e74705SXin Li return;
2602*67e74705SXin Li }
2603*67e74705SXin Li }
2604*67e74705SXin Li
2605*67e74705SXin Li Inherited::VisitUnaryOperator(E);
2606*67e74705SXin Li }
2607*67e74705SXin Li };
2608*67e74705SXin Li
2609*67e74705SXin Li // Diagnose value-uses of fields to initialize themselves, e.g.
2610*67e74705SXin Li // foo(foo)
2611*67e74705SXin Li // where foo is not also a parameter to the constructor.
2612*67e74705SXin Li // Also diagnose across field uninitialized use such as
2613*67e74705SXin Li // x(y), y(x)
2614*67e74705SXin Li // TODO: implement -Wuninitialized and fold this into that framework.
DiagnoseUninitializedFields(Sema & SemaRef,const CXXConstructorDecl * Constructor)2615*67e74705SXin Li static void DiagnoseUninitializedFields(
2616*67e74705SXin Li Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2617*67e74705SXin Li
2618*67e74705SXin Li if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2619*67e74705SXin Li Constructor->getLocation())) {
2620*67e74705SXin Li return;
2621*67e74705SXin Li }
2622*67e74705SXin Li
2623*67e74705SXin Li if (Constructor->isInvalidDecl())
2624*67e74705SXin Li return;
2625*67e74705SXin Li
2626*67e74705SXin Li const CXXRecordDecl *RD = Constructor->getParent();
2627*67e74705SXin Li
2628*67e74705SXin Li if (RD->getDescribedClassTemplate())
2629*67e74705SXin Li return;
2630*67e74705SXin Li
2631*67e74705SXin Li // Holds fields that are uninitialized.
2632*67e74705SXin Li llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2633*67e74705SXin Li
2634*67e74705SXin Li // At the beginning, all fields are uninitialized.
2635*67e74705SXin Li for (auto *I : RD->decls()) {
2636*67e74705SXin Li if (auto *FD = dyn_cast<FieldDecl>(I)) {
2637*67e74705SXin Li UninitializedFields.insert(FD);
2638*67e74705SXin Li } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2639*67e74705SXin Li UninitializedFields.insert(IFD->getAnonField());
2640*67e74705SXin Li }
2641*67e74705SXin Li }
2642*67e74705SXin Li
2643*67e74705SXin Li llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2644*67e74705SXin Li for (auto I : RD->bases())
2645*67e74705SXin Li UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2646*67e74705SXin Li
2647*67e74705SXin Li if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2648*67e74705SXin Li return;
2649*67e74705SXin Li
2650*67e74705SXin Li UninitializedFieldVisitor UninitializedChecker(SemaRef,
2651*67e74705SXin Li UninitializedFields,
2652*67e74705SXin Li UninitializedBaseClasses);
2653*67e74705SXin Li
2654*67e74705SXin Li for (const auto *FieldInit : Constructor->inits()) {
2655*67e74705SXin Li if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2656*67e74705SXin Li break;
2657*67e74705SXin Li
2658*67e74705SXin Li Expr *InitExpr = FieldInit->getInit();
2659*67e74705SXin Li if (!InitExpr)
2660*67e74705SXin Li continue;
2661*67e74705SXin Li
2662*67e74705SXin Li if (CXXDefaultInitExpr *Default =
2663*67e74705SXin Li dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2664*67e74705SXin Li InitExpr = Default->getExpr();
2665*67e74705SXin Li if (!InitExpr)
2666*67e74705SXin Li continue;
2667*67e74705SXin Li // In class initializers will point to the constructor.
2668*67e74705SXin Li UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2669*67e74705SXin Li FieldInit->getAnyMember(),
2670*67e74705SXin Li FieldInit->getBaseClass());
2671*67e74705SXin Li } else {
2672*67e74705SXin Li UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2673*67e74705SXin Li FieldInit->getAnyMember(),
2674*67e74705SXin Li FieldInit->getBaseClass());
2675*67e74705SXin Li }
2676*67e74705SXin Li }
2677*67e74705SXin Li }
2678*67e74705SXin Li } // namespace
2679*67e74705SXin Li
2680*67e74705SXin Li /// \brief Enter a new C++ default initializer scope. After calling this, the
2681*67e74705SXin Li /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2682*67e74705SXin Li /// parsing or instantiating the initializer failed.
ActOnStartCXXInClassMemberInitializer()2683*67e74705SXin Li void Sema::ActOnStartCXXInClassMemberInitializer() {
2684*67e74705SXin Li // Create a synthetic function scope to represent the call to the constructor
2685*67e74705SXin Li // that notionally surrounds a use of this initializer.
2686*67e74705SXin Li PushFunctionScope();
2687*67e74705SXin Li }
2688*67e74705SXin Li
2689*67e74705SXin Li /// \brief This is invoked after parsing an in-class initializer for a
2690*67e74705SXin Li /// non-static C++ class member, and after instantiating an in-class initializer
2691*67e74705SXin Li /// in a class template. Such actions are deferred until the class is complete.
ActOnFinishCXXInClassMemberInitializer(Decl * D,SourceLocation InitLoc,Expr * InitExpr)2692*67e74705SXin Li void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2693*67e74705SXin Li SourceLocation InitLoc,
2694*67e74705SXin Li Expr *InitExpr) {
2695*67e74705SXin Li // Pop the notional constructor scope we created earlier.
2696*67e74705SXin Li PopFunctionScopeInfo(nullptr, D);
2697*67e74705SXin Li
2698*67e74705SXin Li FieldDecl *FD = dyn_cast<FieldDecl>(D);
2699*67e74705SXin Li assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2700*67e74705SXin Li "must set init style when field is created");
2701*67e74705SXin Li
2702*67e74705SXin Li if (!InitExpr) {
2703*67e74705SXin Li D->setInvalidDecl();
2704*67e74705SXin Li if (FD)
2705*67e74705SXin Li FD->removeInClassInitializer();
2706*67e74705SXin Li return;
2707*67e74705SXin Li }
2708*67e74705SXin Li
2709*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2710*67e74705SXin Li FD->setInvalidDecl();
2711*67e74705SXin Li FD->removeInClassInitializer();
2712*67e74705SXin Li return;
2713*67e74705SXin Li }
2714*67e74705SXin Li
2715*67e74705SXin Li ExprResult Init = InitExpr;
2716*67e74705SXin Li if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2717*67e74705SXin Li InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2718*67e74705SXin Li InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2719*67e74705SXin Li ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2720*67e74705SXin Li : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2721*67e74705SXin Li InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2722*67e74705SXin Li Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2723*67e74705SXin Li if (Init.isInvalid()) {
2724*67e74705SXin Li FD->setInvalidDecl();
2725*67e74705SXin Li return;
2726*67e74705SXin Li }
2727*67e74705SXin Li }
2728*67e74705SXin Li
2729*67e74705SXin Li // C++11 [class.base.init]p7:
2730*67e74705SXin Li // The initialization of each base and member constitutes a
2731*67e74705SXin Li // full-expression.
2732*67e74705SXin Li Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2733*67e74705SXin Li if (Init.isInvalid()) {
2734*67e74705SXin Li FD->setInvalidDecl();
2735*67e74705SXin Li return;
2736*67e74705SXin Li }
2737*67e74705SXin Li
2738*67e74705SXin Li InitExpr = Init.get();
2739*67e74705SXin Li
2740*67e74705SXin Li FD->setInClassInitializer(InitExpr);
2741*67e74705SXin Li }
2742*67e74705SXin Li
2743*67e74705SXin Li /// \brief Find the direct and/or virtual base specifiers that
2744*67e74705SXin Li /// correspond to the given base type, for use in base initialization
2745*67e74705SXin Li /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)2746*67e74705SXin Li static bool FindBaseInitializer(Sema &SemaRef,
2747*67e74705SXin Li CXXRecordDecl *ClassDecl,
2748*67e74705SXin Li QualType BaseType,
2749*67e74705SXin Li const CXXBaseSpecifier *&DirectBaseSpec,
2750*67e74705SXin Li const CXXBaseSpecifier *&VirtualBaseSpec) {
2751*67e74705SXin Li // First, check for a direct base class.
2752*67e74705SXin Li DirectBaseSpec = nullptr;
2753*67e74705SXin Li for (const auto &Base : ClassDecl->bases()) {
2754*67e74705SXin Li if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2755*67e74705SXin Li // We found a direct base of this type. That's what we're
2756*67e74705SXin Li // initializing.
2757*67e74705SXin Li DirectBaseSpec = &Base;
2758*67e74705SXin Li break;
2759*67e74705SXin Li }
2760*67e74705SXin Li }
2761*67e74705SXin Li
2762*67e74705SXin Li // Check for a virtual base class.
2763*67e74705SXin Li // FIXME: We might be able to short-circuit this if we know in advance that
2764*67e74705SXin Li // there are no virtual bases.
2765*67e74705SXin Li VirtualBaseSpec = nullptr;
2766*67e74705SXin Li if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2767*67e74705SXin Li // We haven't found a base yet; search the class hierarchy for a
2768*67e74705SXin Li // virtual base class.
2769*67e74705SXin Li CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770*67e74705SXin Li /*DetectVirtual=*/false);
2771*67e74705SXin Li if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2772*67e74705SXin Li SemaRef.Context.getTypeDeclType(ClassDecl),
2773*67e74705SXin Li BaseType, Paths)) {
2774*67e74705SXin Li for (CXXBasePaths::paths_iterator Path = Paths.begin();
2775*67e74705SXin Li Path != Paths.end(); ++Path) {
2776*67e74705SXin Li if (Path->back().Base->isVirtual()) {
2777*67e74705SXin Li VirtualBaseSpec = Path->back().Base;
2778*67e74705SXin Li break;
2779*67e74705SXin Li }
2780*67e74705SXin Li }
2781*67e74705SXin Li }
2782*67e74705SXin Li }
2783*67e74705SXin Li
2784*67e74705SXin Li return DirectBaseSpec || VirtualBaseSpec;
2785*67e74705SXin Li }
2786*67e74705SXin Li
2787*67e74705SXin Li /// \brief Handle a C++ member initializer using braced-init-list syntax.
2788*67e74705SXin Li MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * InitList,SourceLocation EllipsisLoc)2789*67e74705SXin Li Sema::ActOnMemInitializer(Decl *ConstructorD,
2790*67e74705SXin Li Scope *S,
2791*67e74705SXin Li CXXScopeSpec &SS,
2792*67e74705SXin Li IdentifierInfo *MemberOrBase,
2793*67e74705SXin Li ParsedType TemplateTypeTy,
2794*67e74705SXin Li const DeclSpec &DS,
2795*67e74705SXin Li SourceLocation IdLoc,
2796*67e74705SXin Li Expr *InitList,
2797*67e74705SXin Li SourceLocation EllipsisLoc) {
2798*67e74705SXin Li return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2799*67e74705SXin Li DS, IdLoc, InitList,
2800*67e74705SXin Li EllipsisLoc);
2801*67e74705SXin Li }
2802*67e74705SXin Li
2803*67e74705SXin Li /// \brief Handle a C++ member initializer using parentheses syntax.
2804*67e74705SXin Li MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,SourceLocation EllipsisLoc)2805*67e74705SXin Li Sema::ActOnMemInitializer(Decl *ConstructorD,
2806*67e74705SXin Li Scope *S,
2807*67e74705SXin Li CXXScopeSpec &SS,
2808*67e74705SXin Li IdentifierInfo *MemberOrBase,
2809*67e74705SXin Li ParsedType TemplateTypeTy,
2810*67e74705SXin Li const DeclSpec &DS,
2811*67e74705SXin Li SourceLocation IdLoc,
2812*67e74705SXin Li SourceLocation LParenLoc,
2813*67e74705SXin Li ArrayRef<Expr *> Args,
2814*67e74705SXin Li SourceLocation RParenLoc,
2815*67e74705SXin Li SourceLocation EllipsisLoc) {
2816*67e74705SXin Li Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2817*67e74705SXin Li Args, RParenLoc);
2818*67e74705SXin Li return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2819*67e74705SXin Li DS, IdLoc, List, EllipsisLoc);
2820*67e74705SXin Li }
2821*67e74705SXin Li
2822*67e74705SXin Li namespace {
2823*67e74705SXin Li
2824*67e74705SXin Li // Callback to only accept typo corrections that can be a valid C++ member
2825*67e74705SXin Li // intializer: either a non-static field member or a base class.
2826*67e74705SXin Li class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2827*67e74705SXin Li public:
MemInitializerValidatorCCC(CXXRecordDecl * ClassDecl)2828*67e74705SXin Li explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2829*67e74705SXin Li : ClassDecl(ClassDecl) {}
2830*67e74705SXin Li
ValidateCandidate(const TypoCorrection & candidate)2831*67e74705SXin Li bool ValidateCandidate(const TypoCorrection &candidate) override {
2832*67e74705SXin Li if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2833*67e74705SXin Li if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2834*67e74705SXin Li return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2835*67e74705SXin Li return isa<TypeDecl>(ND);
2836*67e74705SXin Li }
2837*67e74705SXin Li return false;
2838*67e74705SXin Li }
2839*67e74705SXin Li
2840*67e74705SXin Li private:
2841*67e74705SXin Li CXXRecordDecl *ClassDecl;
2842*67e74705SXin Li };
2843*67e74705SXin Li
2844*67e74705SXin Li }
2845*67e74705SXin Li
2846*67e74705SXin Li /// \brief Handle a C++ member initializer.
2847*67e74705SXin Li MemInitResult
BuildMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,const DeclSpec & DS,SourceLocation IdLoc,Expr * Init,SourceLocation EllipsisLoc)2848*67e74705SXin Li Sema::BuildMemInitializer(Decl *ConstructorD,
2849*67e74705SXin Li Scope *S,
2850*67e74705SXin Li CXXScopeSpec &SS,
2851*67e74705SXin Li IdentifierInfo *MemberOrBase,
2852*67e74705SXin Li ParsedType TemplateTypeTy,
2853*67e74705SXin Li const DeclSpec &DS,
2854*67e74705SXin Li SourceLocation IdLoc,
2855*67e74705SXin Li Expr *Init,
2856*67e74705SXin Li SourceLocation EllipsisLoc) {
2857*67e74705SXin Li ExprResult Res = CorrectDelayedTyposInExpr(Init);
2858*67e74705SXin Li if (!Res.isUsable())
2859*67e74705SXin Li return true;
2860*67e74705SXin Li Init = Res.get();
2861*67e74705SXin Li
2862*67e74705SXin Li if (!ConstructorD)
2863*67e74705SXin Li return true;
2864*67e74705SXin Li
2865*67e74705SXin Li AdjustDeclIfTemplate(ConstructorD);
2866*67e74705SXin Li
2867*67e74705SXin Li CXXConstructorDecl *Constructor
2868*67e74705SXin Li = dyn_cast<CXXConstructorDecl>(ConstructorD);
2869*67e74705SXin Li if (!Constructor) {
2870*67e74705SXin Li // The user wrote a constructor initializer on a function that is
2871*67e74705SXin Li // not a C++ constructor. Ignore the error for now, because we may
2872*67e74705SXin Li // have more member initializers coming; we'll diagnose it just
2873*67e74705SXin Li // once in ActOnMemInitializers.
2874*67e74705SXin Li return true;
2875*67e74705SXin Li }
2876*67e74705SXin Li
2877*67e74705SXin Li CXXRecordDecl *ClassDecl = Constructor->getParent();
2878*67e74705SXin Li
2879*67e74705SXin Li // C++ [class.base.init]p2:
2880*67e74705SXin Li // Names in a mem-initializer-id are looked up in the scope of the
2881*67e74705SXin Li // constructor's class and, if not found in that scope, are looked
2882*67e74705SXin Li // up in the scope containing the constructor's definition.
2883*67e74705SXin Li // [Note: if the constructor's class contains a member with the
2884*67e74705SXin Li // same name as a direct or virtual base class of the class, a
2885*67e74705SXin Li // mem-initializer-id naming the member or base class and composed
2886*67e74705SXin Li // of a single identifier refers to the class member. A
2887*67e74705SXin Li // mem-initializer-id for the hidden base class may be specified
2888*67e74705SXin Li // using a qualified name. ]
2889*67e74705SXin Li if (!SS.getScopeRep() && !TemplateTypeTy) {
2890*67e74705SXin Li // Look for a member, first.
2891*67e74705SXin Li DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2892*67e74705SXin Li if (!Result.empty()) {
2893*67e74705SXin Li ValueDecl *Member;
2894*67e74705SXin Li if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2895*67e74705SXin Li (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2896*67e74705SXin Li if (EllipsisLoc.isValid())
2897*67e74705SXin Li Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2898*67e74705SXin Li << MemberOrBase
2899*67e74705SXin Li << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2900*67e74705SXin Li
2901*67e74705SXin Li return BuildMemberInitializer(Member, Init, IdLoc);
2902*67e74705SXin Li }
2903*67e74705SXin Li }
2904*67e74705SXin Li }
2905*67e74705SXin Li // It didn't name a member, so see if it names a class.
2906*67e74705SXin Li QualType BaseType;
2907*67e74705SXin Li TypeSourceInfo *TInfo = nullptr;
2908*67e74705SXin Li
2909*67e74705SXin Li if (TemplateTypeTy) {
2910*67e74705SXin Li BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2911*67e74705SXin Li } else if (DS.getTypeSpecType() == TST_decltype) {
2912*67e74705SXin Li BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2913*67e74705SXin Li } else {
2914*67e74705SXin Li LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2915*67e74705SXin Li LookupParsedName(R, S, &SS);
2916*67e74705SXin Li
2917*67e74705SXin Li TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2918*67e74705SXin Li if (!TyD) {
2919*67e74705SXin Li if (R.isAmbiguous()) return true;
2920*67e74705SXin Li
2921*67e74705SXin Li // We don't want access-control diagnostics here.
2922*67e74705SXin Li R.suppressDiagnostics();
2923*67e74705SXin Li
2924*67e74705SXin Li if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2925*67e74705SXin Li bool NotUnknownSpecialization = false;
2926*67e74705SXin Li DeclContext *DC = computeDeclContext(SS, false);
2927*67e74705SXin Li if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2928*67e74705SXin Li NotUnknownSpecialization = !Record->hasAnyDependentBases();
2929*67e74705SXin Li
2930*67e74705SXin Li if (!NotUnknownSpecialization) {
2931*67e74705SXin Li // When the scope specifier can refer to a member of an unknown
2932*67e74705SXin Li // specialization, we take it as a type name.
2933*67e74705SXin Li BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2934*67e74705SXin Li SS.getWithLocInContext(Context),
2935*67e74705SXin Li *MemberOrBase, IdLoc);
2936*67e74705SXin Li if (BaseType.isNull())
2937*67e74705SXin Li return true;
2938*67e74705SXin Li
2939*67e74705SXin Li R.clear();
2940*67e74705SXin Li R.setLookupName(MemberOrBase);
2941*67e74705SXin Li }
2942*67e74705SXin Li }
2943*67e74705SXin Li
2944*67e74705SXin Li // If no results were found, try to correct typos.
2945*67e74705SXin Li TypoCorrection Corr;
2946*67e74705SXin Li if (R.empty() && BaseType.isNull() &&
2947*67e74705SXin Li (Corr = CorrectTypo(
2948*67e74705SXin Li R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2949*67e74705SXin Li llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2950*67e74705SXin Li CTK_ErrorRecovery, ClassDecl))) {
2951*67e74705SXin Li if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2952*67e74705SXin Li // We have found a non-static data member with a similar
2953*67e74705SXin Li // name to what was typed; complain and initialize that
2954*67e74705SXin Li // member.
2955*67e74705SXin Li diagnoseTypo(Corr,
2956*67e74705SXin Li PDiag(diag::err_mem_init_not_member_or_class_suggest)
2957*67e74705SXin Li << MemberOrBase << true);
2958*67e74705SXin Li return BuildMemberInitializer(Member, Init, IdLoc);
2959*67e74705SXin Li } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2960*67e74705SXin Li const CXXBaseSpecifier *DirectBaseSpec;
2961*67e74705SXin Li const CXXBaseSpecifier *VirtualBaseSpec;
2962*67e74705SXin Li if (FindBaseInitializer(*this, ClassDecl,
2963*67e74705SXin Li Context.getTypeDeclType(Type),
2964*67e74705SXin Li DirectBaseSpec, VirtualBaseSpec)) {
2965*67e74705SXin Li // We have found a direct or virtual base class with a
2966*67e74705SXin Li // similar name to what was typed; complain and initialize
2967*67e74705SXin Li // that base class.
2968*67e74705SXin Li diagnoseTypo(Corr,
2969*67e74705SXin Li PDiag(diag::err_mem_init_not_member_or_class_suggest)
2970*67e74705SXin Li << MemberOrBase << false,
2971*67e74705SXin Li PDiag() /*Suppress note, we provide our own.*/);
2972*67e74705SXin Li
2973*67e74705SXin Li const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2974*67e74705SXin Li : VirtualBaseSpec;
2975*67e74705SXin Li Diag(BaseSpec->getLocStart(),
2976*67e74705SXin Li diag::note_base_class_specified_here)
2977*67e74705SXin Li << BaseSpec->getType()
2978*67e74705SXin Li << BaseSpec->getSourceRange();
2979*67e74705SXin Li
2980*67e74705SXin Li TyD = Type;
2981*67e74705SXin Li }
2982*67e74705SXin Li }
2983*67e74705SXin Li }
2984*67e74705SXin Li
2985*67e74705SXin Li if (!TyD && BaseType.isNull()) {
2986*67e74705SXin Li Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2987*67e74705SXin Li << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2988*67e74705SXin Li return true;
2989*67e74705SXin Li }
2990*67e74705SXin Li }
2991*67e74705SXin Li
2992*67e74705SXin Li if (BaseType.isNull()) {
2993*67e74705SXin Li BaseType = Context.getTypeDeclType(TyD);
2994*67e74705SXin Li MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2995*67e74705SXin Li if (SS.isSet()) {
2996*67e74705SXin Li BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2997*67e74705SXin Li BaseType);
2998*67e74705SXin Li TInfo = Context.CreateTypeSourceInfo(BaseType);
2999*67e74705SXin Li ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3000*67e74705SXin Li TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3001*67e74705SXin Li TL.setElaboratedKeywordLoc(SourceLocation());
3002*67e74705SXin Li TL.setQualifierLoc(SS.getWithLocInContext(Context));
3003*67e74705SXin Li }
3004*67e74705SXin Li }
3005*67e74705SXin Li }
3006*67e74705SXin Li
3007*67e74705SXin Li if (!TInfo)
3008*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3009*67e74705SXin Li
3010*67e74705SXin Li return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3011*67e74705SXin Li }
3012*67e74705SXin Li
3013*67e74705SXin Li /// Checks a member initializer expression for cases where reference (or
3014*67e74705SXin Li /// pointer) members are bound to by-value parameters (or their addresses).
CheckForDanglingReferenceOrPointer(Sema & S,ValueDecl * Member,Expr * Init,SourceLocation IdLoc)3015*67e74705SXin Li static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3016*67e74705SXin Li Expr *Init,
3017*67e74705SXin Li SourceLocation IdLoc) {
3018*67e74705SXin Li QualType MemberTy = Member->getType();
3019*67e74705SXin Li
3020*67e74705SXin Li // We only handle pointers and references currently.
3021*67e74705SXin Li // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3022*67e74705SXin Li if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3023*67e74705SXin Li return;
3024*67e74705SXin Li
3025*67e74705SXin Li const bool IsPointer = MemberTy->isPointerType();
3026*67e74705SXin Li if (IsPointer) {
3027*67e74705SXin Li if (const UnaryOperator *Op
3028*67e74705SXin Li = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3029*67e74705SXin Li // The only case we're worried about with pointers requires taking the
3030*67e74705SXin Li // address.
3031*67e74705SXin Li if (Op->getOpcode() != UO_AddrOf)
3032*67e74705SXin Li return;
3033*67e74705SXin Li
3034*67e74705SXin Li Init = Op->getSubExpr();
3035*67e74705SXin Li } else {
3036*67e74705SXin Li // We only handle address-of expression initializers for pointers.
3037*67e74705SXin Li return;
3038*67e74705SXin Li }
3039*67e74705SXin Li }
3040*67e74705SXin Li
3041*67e74705SXin Li if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3042*67e74705SXin Li // We only warn when referring to a non-reference parameter declaration.
3043*67e74705SXin Li const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3044*67e74705SXin Li if (!Parameter || Parameter->getType()->isReferenceType())
3045*67e74705SXin Li return;
3046*67e74705SXin Li
3047*67e74705SXin Li S.Diag(Init->getExprLoc(),
3048*67e74705SXin Li IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3049*67e74705SXin Li : diag::warn_bind_ref_member_to_parameter)
3050*67e74705SXin Li << Member << Parameter << Init->getSourceRange();
3051*67e74705SXin Li } else {
3052*67e74705SXin Li // Other initializers are fine.
3053*67e74705SXin Li return;
3054*67e74705SXin Li }
3055*67e74705SXin Li
3056*67e74705SXin Li S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3057*67e74705SXin Li << (unsigned)IsPointer;
3058*67e74705SXin Li }
3059*67e74705SXin Li
3060*67e74705SXin Li MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr * Init,SourceLocation IdLoc)3061*67e74705SXin Li Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3062*67e74705SXin Li SourceLocation IdLoc) {
3063*67e74705SXin Li FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3064*67e74705SXin Li IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3065*67e74705SXin Li assert((DirectMember || IndirectMember) &&
3066*67e74705SXin Li "Member must be a FieldDecl or IndirectFieldDecl");
3067*67e74705SXin Li
3068*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3069*67e74705SXin Li return true;
3070*67e74705SXin Li
3071*67e74705SXin Li if (Member->isInvalidDecl())
3072*67e74705SXin Li return true;
3073*67e74705SXin Li
3074*67e74705SXin Li MultiExprArg Args;
3075*67e74705SXin Li if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3076*67e74705SXin Li Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3077*67e74705SXin Li } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3078*67e74705SXin Li Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3079*67e74705SXin Li } else {
3080*67e74705SXin Li // Template instantiation doesn't reconstruct ParenListExprs for us.
3081*67e74705SXin Li Args = Init;
3082*67e74705SXin Li }
3083*67e74705SXin Li
3084*67e74705SXin Li SourceRange InitRange = Init->getSourceRange();
3085*67e74705SXin Li
3086*67e74705SXin Li if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3087*67e74705SXin Li // Can't check initialization for a member of dependent type or when
3088*67e74705SXin Li // any of the arguments are type-dependent expressions.
3089*67e74705SXin Li DiscardCleanupsInEvaluationContext();
3090*67e74705SXin Li } else {
3091*67e74705SXin Li bool InitList = false;
3092*67e74705SXin Li if (isa<InitListExpr>(Init)) {
3093*67e74705SXin Li InitList = true;
3094*67e74705SXin Li Args = Init;
3095*67e74705SXin Li }
3096*67e74705SXin Li
3097*67e74705SXin Li // Initialize the member.
3098*67e74705SXin Li InitializedEntity MemberEntity =
3099*67e74705SXin Li DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3100*67e74705SXin Li : InitializedEntity::InitializeMember(IndirectMember,
3101*67e74705SXin Li nullptr);
3102*67e74705SXin Li InitializationKind Kind =
3103*67e74705SXin Li InitList ? InitializationKind::CreateDirectList(IdLoc)
3104*67e74705SXin Li : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3105*67e74705SXin Li InitRange.getEnd());
3106*67e74705SXin Li
3107*67e74705SXin Li InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3108*67e74705SXin Li ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3109*67e74705SXin Li nullptr);
3110*67e74705SXin Li if (MemberInit.isInvalid())
3111*67e74705SXin Li return true;
3112*67e74705SXin Li
3113*67e74705SXin Li CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3114*67e74705SXin Li
3115*67e74705SXin Li // C++11 [class.base.init]p7:
3116*67e74705SXin Li // The initialization of each base and member constitutes a
3117*67e74705SXin Li // full-expression.
3118*67e74705SXin Li MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3119*67e74705SXin Li if (MemberInit.isInvalid())
3120*67e74705SXin Li return true;
3121*67e74705SXin Li
3122*67e74705SXin Li Init = MemberInit.get();
3123*67e74705SXin Li }
3124*67e74705SXin Li
3125*67e74705SXin Li if (DirectMember) {
3126*67e74705SXin Li return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3127*67e74705SXin Li InitRange.getBegin(), Init,
3128*67e74705SXin Li InitRange.getEnd());
3129*67e74705SXin Li } else {
3130*67e74705SXin Li return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3131*67e74705SXin Li InitRange.getBegin(), Init,
3132*67e74705SXin Li InitRange.getEnd());
3133*67e74705SXin Li }
3134*67e74705SXin Li }
3135*67e74705SXin Li
3136*67e74705SXin Li MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr * Init,CXXRecordDecl * ClassDecl)3137*67e74705SXin Li Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3138*67e74705SXin Li CXXRecordDecl *ClassDecl) {
3139*67e74705SXin Li SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3140*67e74705SXin Li if (!LangOpts.CPlusPlus11)
3141*67e74705SXin Li return Diag(NameLoc, diag::err_delegating_ctor)
3142*67e74705SXin Li << TInfo->getTypeLoc().getLocalSourceRange();
3143*67e74705SXin Li Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3144*67e74705SXin Li
3145*67e74705SXin Li bool InitList = true;
3146*67e74705SXin Li MultiExprArg Args = Init;
3147*67e74705SXin Li if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3148*67e74705SXin Li InitList = false;
3149*67e74705SXin Li Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3150*67e74705SXin Li }
3151*67e74705SXin Li
3152*67e74705SXin Li SourceRange InitRange = Init->getSourceRange();
3153*67e74705SXin Li // Initialize the object.
3154*67e74705SXin Li InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3155*67e74705SXin Li QualType(ClassDecl->getTypeForDecl(), 0));
3156*67e74705SXin Li InitializationKind Kind =
3157*67e74705SXin Li InitList ? InitializationKind::CreateDirectList(NameLoc)
3158*67e74705SXin Li : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3159*67e74705SXin Li InitRange.getEnd());
3160*67e74705SXin Li InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3161*67e74705SXin Li ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3162*67e74705SXin Li Args, nullptr);
3163*67e74705SXin Li if (DelegationInit.isInvalid())
3164*67e74705SXin Li return true;
3165*67e74705SXin Li
3166*67e74705SXin Li assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3167*67e74705SXin Li "Delegating constructor with no target?");
3168*67e74705SXin Li
3169*67e74705SXin Li // C++11 [class.base.init]p7:
3170*67e74705SXin Li // The initialization of each base and member constitutes a
3171*67e74705SXin Li // full-expression.
3172*67e74705SXin Li DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3173*67e74705SXin Li InitRange.getBegin());
3174*67e74705SXin Li if (DelegationInit.isInvalid())
3175*67e74705SXin Li return true;
3176*67e74705SXin Li
3177*67e74705SXin Li // If we are in a dependent context, template instantiation will
3178*67e74705SXin Li // perform this type-checking again. Just save the arguments that we
3179*67e74705SXin Li // received in a ParenListExpr.
3180*67e74705SXin Li // FIXME: This isn't quite ideal, since our ASTs don't capture all
3181*67e74705SXin Li // of the information that we have about the base
3182*67e74705SXin Li // initializer. However, deconstructing the ASTs is a dicey process,
3183*67e74705SXin Li // and this approach is far more likely to get the corner cases right.
3184*67e74705SXin Li if (CurContext->isDependentContext())
3185*67e74705SXin Li DelegationInit = Init;
3186*67e74705SXin Li
3187*67e74705SXin Li return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3188*67e74705SXin Li DelegationInit.getAs<Expr>(),
3189*67e74705SXin Li InitRange.getEnd());
3190*67e74705SXin Li }
3191*67e74705SXin Li
3192*67e74705SXin Li MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr * Init,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)3193*67e74705SXin Li Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3194*67e74705SXin Li Expr *Init, CXXRecordDecl *ClassDecl,
3195*67e74705SXin Li SourceLocation EllipsisLoc) {
3196*67e74705SXin Li SourceLocation BaseLoc
3197*67e74705SXin Li = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3198*67e74705SXin Li
3199*67e74705SXin Li if (!BaseType->isDependentType() && !BaseType->isRecordType())
3200*67e74705SXin Li return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3201*67e74705SXin Li << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3202*67e74705SXin Li
3203*67e74705SXin Li // C++ [class.base.init]p2:
3204*67e74705SXin Li // [...] Unless the mem-initializer-id names a nonstatic data
3205*67e74705SXin Li // member of the constructor's class or a direct or virtual base
3206*67e74705SXin Li // of that class, the mem-initializer is ill-formed. A
3207*67e74705SXin Li // mem-initializer-list can initialize a base class using any
3208*67e74705SXin Li // name that denotes that base class type.
3209*67e74705SXin Li bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3210*67e74705SXin Li
3211*67e74705SXin Li SourceRange InitRange = Init->getSourceRange();
3212*67e74705SXin Li if (EllipsisLoc.isValid()) {
3213*67e74705SXin Li // This is a pack expansion.
3214*67e74705SXin Li if (!BaseType->containsUnexpandedParameterPack()) {
3215*67e74705SXin Li Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3216*67e74705SXin Li << SourceRange(BaseLoc, InitRange.getEnd());
3217*67e74705SXin Li
3218*67e74705SXin Li EllipsisLoc = SourceLocation();
3219*67e74705SXin Li }
3220*67e74705SXin Li } else {
3221*67e74705SXin Li // Check for any unexpanded parameter packs.
3222*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3223*67e74705SXin Li return true;
3224*67e74705SXin Li
3225*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3226*67e74705SXin Li return true;
3227*67e74705SXin Li }
3228*67e74705SXin Li
3229*67e74705SXin Li // Check for direct and virtual base classes.
3230*67e74705SXin Li const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3231*67e74705SXin Li const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3232*67e74705SXin Li if (!Dependent) {
3233*67e74705SXin Li if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3234*67e74705SXin Li BaseType))
3235*67e74705SXin Li return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3236*67e74705SXin Li
3237*67e74705SXin Li FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3238*67e74705SXin Li VirtualBaseSpec);
3239*67e74705SXin Li
3240*67e74705SXin Li // C++ [base.class.init]p2:
3241*67e74705SXin Li // Unless the mem-initializer-id names a nonstatic data member of the
3242*67e74705SXin Li // constructor's class or a direct or virtual base of that class, the
3243*67e74705SXin Li // mem-initializer is ill-formed.
3244*67e74705SXin Li if (!DirectBaseSpec && !VirtualBaseSpec) {
3245*67e74705SXin Li // If the class has any dependent bases, then it's possible that
3246*67e74705SXin Li // one of those types will resolve to the same type as
3247*67e74705SXin Li // BaseType. Therefore, just treat this as a dependent base
3248*67e74705SXin Li // class initialization. FIXME: Should we try to check the
3249*67e74705SXin Li // initialization anyway? It seems odd.
3250*67e74705SXin Li if (ClassDecl->hasAnyDependentBases())
3251*67e74705SXin Li Dependent = true;
3252*67e74705SXin Li else
3253*67e74705SXin Li return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3254*67e74705SXin Li << BaseType << Context.getTypeDeclType(ClassDecl)
3255*67e74705SXin Li << BaseTInfo->getTypeLoc().getLocalSourceRange();
3256*67e74705SXin Li }
3257*67e74705SXin Li }
3258*67e74705SXin Li
3259*67e74705SXin Li if (Dependent) {
3260*67e74705SXin Li DiscardCleanupsInEvaluationContext();
3261*67e74705SXin Li
3262*67e74705SXin Li return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3263*67e74705SXin Li /*IsVirtual=*/false,
3264*67e74705SXin Li InitRange.getBegin(), Init,
3265*67e74705SXin Li InitRange.getEnd(), EllipsisLoc);
3266*67e74705SXin Li }
3267*67e74705SXin Li
3268*67e74705SXin Li // C++ [base.class.init]p2:
3269*67e74705SXin Li // If a mem-initializer-id is ambiguous because it designates both
3270*67e74705SXin Li // a direct non-virtual base class and an inherited virtual base
3271*67e74705SXin Li // class, the mem-initializer is ill-formed.
3272*67e74705SXin Li if (DirectBaseSpec && VirtualBaseSpec)
3273*67e74705SXin Li return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3274*67e74705SXin Li << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3275*67e74705SXin Li
3276*67e74705SXin Li const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3277*67e74705SXin Li if (!BaseSpec)
3278*67e74705SXin Li BaseSpec = VirtualBaseSpec;
3279*67e74705SXin Li
3280*67e74705SXin Li // Initialize the base.
3281*67e74705SXin Li bool InitList = true;
3282*67e74705SXin Li MultiExprArg Args = Init;
3283*67e74705SXin Li if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3284*67e74705SXin Li InitList = false;
3285*67e74705SXin Li Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3286*67e74705SXin Li }
3287*67e74705SXin Li
3288*67e74705SXin Li InitializedEntity BaseEntity =
3289*67e74705SXin Li InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3290*67e74705SXin Li InitializationKind Kind =
3291*67e74705SXin Li InitList ? InitializationKind::CreateDirectList(BaseLoc)
3292*67e74705SXin Li : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3293*67e74705SXin Li InitRange.getEnd());
3294*67e74705SXin Li InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3295*67e74705SXin Li ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3296*67e74705SXin Li if (BaseInit.isInvalid())
3297*67e74705SXin Li return true;
3298*67e74705SXin Li
3299*67e74705SXin Li // C++11 [class.base.init]p7:
3300*67e74705SXin Li // The initialization of each base and member constitutes a
3301*67e74705SXin Li // full-expression.
3302*67e74705SXin Li BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3303*67e74705SXin Li if (BaseInit.isInvalid())
3304*67e74705SXin Li return true;
3305*67e74705SXin Li
3306*67e74705SXin Li // If we are in a dependent context, template instantiation will
3307*67e74705SXin Li // perform this type-checking again. Just save the arguments that we
3308*67e74705SXin Li // received in a ParenListExpr.
3309*67e74705SXin Li // FIXME: This isn't quite ideal, since our ASTs don't capture all
3310*67e74705SXin Li // of the information that we have about the base
3311*67e74705SXin Li // initializer. However, deconstructing the ASTs is a dicey process,
3312*67e74705SXin Li // and this approach is far more likely to get the corner cases right.
3313*67e74705SXin Li if (CurContext->isDependentContext())
3314*67e74705SXin Li BaseInit = Init;
3315*67e74705SXin Li
3316*67e74705SXin Li return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3317*67e74705SXin Li BaseSpec->isVirtual(),
3318*67e74705SXin Li InitRange.getBegin(),
3319*67e74705SXin Li BaseInit.getAs<Expr>(),
3320*67e74705SXin Li InitRange.getEnd(), EllipsisLoc);
3321*67e74705SXin Li }
3322*67e74705SXin Li
3323*67e74705SXin Li // Create a static_cast\<T&&>(expr).
CastForMoving(Sema & SemaRef,Expr * E,QualType T=QualType ())3324*67e74705SXin Li static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3325*67e74705SXin Li if (T.isNull()) T = E->getType();
3326*67e74705SXin Li QualType TargetType = SemaRef.BuildReferenceType(
3327*67e74705SXin Li T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3328*67e74705SXin Li SourceLocation ExprLoc = E->getLocStart();
3329*67e74705SXin Li TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3330*67e74705SXin Li TargetType, ExprLoc);
3331*67e74705SXin Li
3332*67e74705SXin Li return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3333*67e74705SXin Li SourceRange(ExprLoc, ExprLoc),
3334*67e74705SXin Li E->getSourceRange()).get();
3335*67e74705SXin Li }
3336*67e74705SXin Li
3337*67e74705SXin Li /// ImplicitInitializerKind - How an implicit base or member initializer should
3338*67e74705SXin Li /// initialize its base or member.
3339*67e74705SXin Li enum ImplicitInitializerKind {
3340*67e74705SXin Li IIK_Default,
3341*67e74705SXin Li IIK_Copy,
3342*67e74705SXin Li IIK_Move,
3343*67e74705SXin Li IIK_Inherit
3344*67e74705SXin Li };
3345*67e74705SXin Li
3346*67e74705SXin Li static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)3347*67e74705SXin Li BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3348*67e74705SXin Li ImplicitInitializerKind ImplicitInitKind,
3349*67e74705SXin Li CXXBaseSpecifier *BaseSpec,
3350*67e74705SXin Li bool IsInheritedVirtualBase,
3351*67e74705SXin Li CXXCtorInitializer *&CXXBaseInit) {
3352*67e74705SXin Li InitializedEntity InitEntity
3353*67e74705SXin Li = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3354*67e74705SXin Li IsInheritedVirtualBase);
3355*67e74705SXin Li
3356*67e74705SXin Li ExprResult BaseInit;
3357*67e74705SXin Li
3358*67e74705SXin Li switch (ImplicitInitKind) {
3359*67e74705SXin Li case IIK_Inherit:
3360*67e74705SXin Li case IIK_Default: {
3361*67e74705SXin Li InitializationKind InitKind
3362*67e74705SXin Li = InitializationKind::CreateDefault(Constructor->getLocation());
3363*67e74705SXin Li InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3364*67e74705SXin Li BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3365*67e74705SXin Li break;
3366*67e74705SXin Li }
3367*67e74705SXin Li
3368*67e74705SXin Li case IIK_Move:
3369*67e74705SXin Li case IIK_Copy: {
3370*67e74705SXin Li bool Moving = ImplicitInitKind == IIK_Move;
3371*67e74705SXin Li ParmVarDecl *Param = Constructor->getParamDecl(0);
3372*67e74705SXin Li QualType ParamType = Param->getType().getNonReferenceType();
3373*67e74705SXin Li
3374*67e74705SXin Li Expr *CopyCtorArg =
3375*67e74705SXin Li DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3376*67e74705SXin Li SourceLocation(), Param, false,
3377*67e74705SXin Li Constructor->getLocation(), ParamType,
3378*67e74705SXin Li VK_LValue, nullptr);
3379*67e74705SXin Li
3380*67e74705SXin Li SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3381*67e74705SXin Li
3382*67e74705SXin Li // Cast to the base class to avoid ambiguities.
3383*67e74705SXin Li QualType ArgTy =
3384*67e74705SXin Li SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3385*67e74705SXin Li ParamType.getQualifiers());
3386*67e74705SXin Li
3387*67e74705SXin Li if (Moving) {
3388*67e74705SXin Li CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3389*67e74705SXin Li }
3390*67e74705SXin Li
3391*67e74705SXin Li CXXCastPath BasePath;
3392*67e74705SXin Li BasePath.push_back(BaseSpec);
3393*67e74705SXin Li CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3394*67e74705SXin Li CK_UncheckedDerivedToBase,
3395*67e74705SXin Li Moving ? VK_XValue : VK_LValue,
3396*67e74705SXin Li &BasePath).get();
3397*67e74705SXin Li
3398*67e74705SXin Li InitializationKind InitKind
3399*67e74705SXin Li = InitializationKind::CreateDirect(Constructor->getLocation(),
3400*67e74705SXin Li SourceLocation(), SourceLocation());
3401*67e74705SXin Li InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3402*67e74705SXin Li BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3403*67e74705SXin Li break;
3404*67e74705SXin Li }
3405*67e74705SXin Li }
3406*67e74705SXin Li
3407*67e74705SXin Li BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3408*67e74705SXin Li if (BaseInit.isInvalid())
3409*67e74705SXin Li return true;
3410*67e74705SXin Li
3411*67e74705SXin Li CXXBaseInit =
3412*67e74705SXin Li new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3413*67e74705SXin Li SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3414*67e74705SXin Li SourceLocation()),
3415*67e74705SXin Li BaseSpec->isVirtual(),
3416*67e74705SXin Li SourceLocation(),
3417*67e74705SXin Li BaseInit.getAs<Expr>(),
3418*67e74705SXin Li SourceLocation(),
3419*67e74705SXin Li SourceLocation());
3420*67e74705SXin Li
3421*67e74705SXin Li return false;
3422*67e74705SXin Li }
3423*67e74705SXin Li
RefersToRValueRef(Expr * MemRef)3424*67e74705SXin Li static bool RefersToRValueRef(Expr *MemRef) {
3425*67e74705SXin Li ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3426*67e74705SXin Li return Referenced->getType()->isRValueReferenceType();
3427*67e74705SXin Li }
3428*67e74705SXin Li
3429*67e74705SXin Li static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,IndirectFieldDecl * Indirect,CXXCtorInitializer * & CXXMemberInit)3430*67e74705SXin Li BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3431*67e74705SXin Li ImplicitInitializerKind ImplicitInitKind,
3432*67e74705SXin Li FieldDecl *Field, IndirectFieldDecl *Indirect,
3433*67e74705SXin Li CXXCtorInitializer *&CXXMemberInit) {
3434*67e74705SXin Li if (Field->isInvalidDecl())
3435*67e74705SXin Li return true;
3436*67e74705SXin Li
3437*67e74705SXin Li SourceLocation Loc = Constructor->getLocation();
3438*67e74705SXin Li
3439*67e74705SXin Li if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3440*67e74705SXin Li bool Moving = ImplicitInitKind == IIK_Move;
3441*67e74705SXin Li ParmVarDecl *Param = Constructor->getParamDecl(0);
3442*67e74705SXin Li QualType ParamType = Param->getType().getNonReferenceType();
3443*67e74705SXin Li
3444*67e74705SXin Li // Suppress copying zero-width bitfields.
3445*67e74705SXin Li if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3446*67e74705SXin Li return false;
3447*67e74705SXin Li
3448*67e74705SXin Li Expr *MemberExprBase =
3449*67e74705SXin Li DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3450*67e74705SXin Li SourceLocation(), Param, false,
3451*67e74705SXin Li Loc, ParamType, VK_LValue, nullptr);
3452*67e74705SXin Li
3453*67e74705SXin Li SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3454*67e74705SXin Li
3455*67e74705SXin Li if (Moving) {
3456*67e74705SXin Li MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3457*67e74705SXin Li }
3458*67e74705SXin Li
3459*67e74705SXin Li // Build a reference to this field within the parameter.
3460*67e74705SXin Li CXXScopeSpec SS;
3461*67e74705SXin Li LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3462*67e74705SXin Li Sema::LookupMemberName);
3463*67e74705SXin Li MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3464*67e74705SXin Li : cast<ValueDecl>(Field), AS_public);
3465*67e74705SXin Li MemberLookup.resolveKind();
3466*67e74705SXin Li ExprResult CtorArg
3467*67e74705SXin Li = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3468*67e74705SXin Li ParamType, Loc,
3469*67e74705SXin Li /*IsArrow=*/false,
3470*67e74705SXin Li SS,
3471*67e74705SXin Li /*TemplateKWLoc=*/SourceLocation(),
3472*67e74705SXin Li /*FirstQualifierInScope=*/nullptr,
3473*67e74705SXin Li MemberLookup,
3474*67e74705SXin Li /*TemplateArgs=*/nullptr,
3475*67e74705SXin Li /*S*/nullptr);
3476*67e74705SXin Li if (CtorArg.isInvalid())
3477*67e74705SXin Li return true;
3478*67e74705SXin Li
3479*67e74705SXin Li // C++11 [class.copy]p15:
3480*67e74705SXin Li // - if a member m has rvalue reference type T&&, it is direct-initialized
3481*67e74705SXin Li // with static_cast<T&&>(x.m);
3482*67e74705SXin Li if (RefersToRValueRef(CtorArg.get())) {
3483*67e74705SXin Li CtorArg = CastForMoving(SemaRef, CtorArg.get());
3484*67e74705SXin Li }
3485*67e74705SXin Li
3486*67e74705SXin Li // When the field we are copying is an array, create index variables for
3487*67e74705SXin Li // each dimension of the array. We use these index variables to subscript
3488*67e74705SXin Li // the source array, and other clients (e.g., CodeGen) will perform the
3489*67e74705SXin Li // necessary iteration with these index variables.
3490*67e74705SXin Li SmallVector<VarDecl *, 4> IndexVariables;
3491*67e74705SXin Li QualType BaseType = Field->getType();
3492*67e74705SXin Li QualType SizeType = SemaRef.Context.getSizeType();
3493*67e74705SXin Li bool InitializingArray = false;
3494*67e74705SXin Li while (const ConstantArrayType *Array
3495*67e74705SXin Li = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3496*67e74705SXin Li InitializingArray = true;
3497*67e74705SXin Li // Create the iteration variable for this array index.
3498*67e74705SXin Li IdentifierInfo *IterationVarName = nullptr;
3499*67e74705SXin Li {
3500*67e74705SXin Li SmallString<8> Str;
3501*67e74705SXin Li llvm::raw_svector_ostream OS(Str);
3502*67e74705SXin Li OS << "__i" << IndexVariables.size();
3503*67e74705SXin Li IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3504*67e74705SXin Li }
3505*67e74705SXin Li VarDecl *IterationVar
3506*67e74705SXin Li = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3507*67e74705SXin Li IterationVarName, SizeType,
3508*67e74705SXin Li SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3509*67e74705SXin Li SC_None);
3510*67e74705SXin Li IndexVariables.push_back(IterationVar);
3511*67e74705SXin Li
3512*67e74705SXin Li // Create a reference to the iteration variable.
3513*67e74705SXin Li ExprResult IterationVarRef
3514*67e74705SXin Li = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3515*67e74705SXin Li assert(!IterationVarRef.isInvalid() &&
3516*67e74705SXin Li "Reference to invented variable cannot fail!");
3517*67e74705SXin Li IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3518*67e74705SXin Li assert(!IterationVarRef.isInvalid() &&
3519*67e74705SXin Li "Conversion of invented variable cannot fail!");
3520*67e74705SXin Li
3521*67e74705SXin Li // Subscript the array with this iteration variable.
3522*67e74705SXin Li CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3523*67e74705SXin Li IterationVarRef.get(),
3524*67e74705SXin Li Loc);
3525*67e74705SXin Li if (CtorArg.isInvalid())
3526*67e74705SXin Li return true;
3527*67e74705SXin Li
3528*67e74705SXin Li BaseType = Array->getElementType();
3529*67e74705SXin Li }
3530*67e74705SXin Li
3531*67e74705SXin Li // The array subscript expression is an lvalue, which is wrong for moving.
3532*67e74705SXin Li if (Moving && InitializingArray)
3533*67e74705SXin Li CtorArg = CastForMoving(SemaRef, CtorArg.get());
3534*67e74705SXin Li
3535*67e74705SXin Li // Construct the entity that we will be initializing. For an array, this
3536*67e74705SXin Li // will be first element in the array, which may require several levels
3537*67e74705SXin Li // of array-subscript entities.
3538*67e74705SXin Li SmallVector<InitializedEntity, 4> Entities;
3539*67e74705SXin Li Entities.reserve(1 + IndexVariables.size());
3540*67e74705SXin Li if (Indirect)
3541*67e74705SXin Li Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3542*67e74705SXin Li else
3543*67e74705SXin Li Entities.push_back(InitializedEntity::InitializeMember(Field));
3544*67e74705SXin Li for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3545*67e74705SXin Li Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3546*67e74705SXin Li 0,
3547*67e74705SXin Li Entities.back()));
3548*67e74705SXin Li
3549*67e74705SXin Li // Direct-initialize to use the copy constructor.
3550*67e74705SXin Li InitializationKind InitKind =
3551*67e74705SXin Li InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3552*67e74705SXin Li
3553*67e74705SXin Li Expr *CtorArgE = CtorArg.getAs<Expr>();
3554*67e74705SXin Li InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3555*67e74705SXin Li CtorArgE);
3556*67e74705SXin Li
3557*67e74705SXin Li ExprResult MemberInit
3558*67e74705SXin Li = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3559*67e74705SXin Li MultiExprArg(&CtorArgE, 1));
3560*67e74705SXin Li MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3561*67e74705SXin Li if (MemberInit.isInvalid())
3562*67e74705SXin Li return true;
3563*67e74705SXin Li
3564*67e74705SXin Li if (Indirect) {
3565*67e74705SXin Li assert(IndexVariables.size() == 0 &&
3566*67e74705SXin Li "Indirect field improperly initialized");
3567*67e74705SXin Li CXXMemberInit
3568*67e74705SXin Li = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3569*67e74705SXin Li Loc, Loc,
3570*67e74705SXin Li MemberInit.getAs<Expr>(),
3571*67e74705SXin Li Loc);
3572*67e74705SXin Li } else
3573*67e74705SXin Li CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3574*67e74705SXin Li Loc, MemberInit.getAs<Expr>(),
3575*67e74705SXin Li Loc,
3576*67e74705SXin Li IndexVariables.data(),
3577*67e74705SXin Li IndexVariables.size());
3578*67e74705SXin Li return false;
3579*67e74705SXin Li }
3580*67e74705SXin Li
3581*67e74705SXin Li assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3582*67e74705SXin Li "Unhandled implicit init kind!");
3583*67e74705SXin Li
3584*67e74705SXin Li QualType FieldBaseElementType =
3585*67e74705SXin Li SemaRef.Context.getBaseElementType(Field->getType());
3586*67e74705SXin Li
3587*67e74705SXin Li if (FieldBaseElementType->isRecordType()) {
3588*67e74705SXin Li InitializedEntity InitEntity
3589*67e74705SXin Li = Indirect? InitializedEntity::InitializeMember(Indirect)
3590*67e74705SXin Li : InitializedEntity::InitializeMember(Field);
3591*67e74705SXin Li InitializationKind InitKind =
3592*67e74705SXin Li InitializationKind::CreateDefault(Loc);
3593*67e74705SXin Li
3594*67e74705SXin Li InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3595*67e74705SXin Li ExprResult MemberInit =
3596*67e74705SXin Li InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3597*67e74705SXin Li
3598*67e74705SXin Li MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3599*67e74705SXin Li if (MemberInit.isInvalid())
3600*67e74705SXin Li return true;
3601*67e74705SXin Li
3602*67e74705SXin Li if (Indirect)
3603*67e74705SXin Li CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3604*67e74705SXin Li Indirect, Loc,
3605*67e74705SXin Li Loc,
3606*67e74705SXin Li MemberInit.get(),
3607*67e74705SXin Li Loc);
3608*67e74705SXin Li else
3609*67e74705SXin Li CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3610*67e74705SXin Li Field, Loc, Loc,
3611*67e74705SXin Li MemberInit.get(),
3612*67e74705SXin Li Loc);
3613*67e74705SXin Li return false;
3614*67e74705SXin Li }
3615*67e74705SXin Li
3616*67e74705SXin Li if (!Field->getParent()->isUnion()) {
3617*67e74705SXin Li if (FieldBaseElementType->isReferenceType()) {
3618*67e74705SXin Li SemaRef.Diag(Constructor->getLocation(),
3619*67e74705SXin Li diag::err_uninitialized_member_in_ctor)
3620*67e74705SXin Li << (int)Constructor->isImplicit()
3621*67e74705SXin Li << SemaRef.Context.getTagDeclType(Constructor->getParent())
3622*67e74705SXin Li << 0 << Field->getDeclName();
3623*67e74705SXin Li SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3624*67e74705SXin Li return true;
3625*67e74705SXin Li }
3626*67e74705SXin Li
3627*67e74705SXin Li if (FieldBaseElementType.isConstQualified()) {
3628*67e74705SXin Li SemaRef.Diag(Constructor->getLocation(),
3629*67e74705SXin Li diag::err_uninitialized_member_in_ctor)
3630*67e74705SXin Li << (int)Constructor->isImplicit()
3631*67e74705SXin Li << SemaRef.Context.getTagDeclType(Constructor->getParent())
3632*67e74705SXin Li << 1 << Field->getDeclName();
3633*67e74705SXin Li SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3634*67e74705SXin Li return true;
3635*67e74705SXin Li }
3636*67e74705SXin Li }
3637*67e74705SXin Li
3638*67e74705SXin Li if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3639*67e74705SXin Li FieldBaseElementType->isObjCRetainableType() &&
3640*67e74705SXin Li FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3641*67e74705SXin Li FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3642*67e74705SXin Li // ARC:
3643*67e74705SXin Li // Default-initialize Objective-C pointers to NULL.
3644*67e74705SXin Li CXXMemberInit
3645*67e74705SXin Li = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3646*67e74705SXin Li Loc, Loc,
3647*67e74705SXin Li new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3648*67e74705SXin Li Loc);
3649*67e74705SXin Li return false;
3650*67e74705SXin Li }
3651*67e74705SXin Li
3652*67e74705SXin Li // Nothing to initialize.
3653*67e74705SXin Li CXXMemberInit = nullptr;
3654*67e74705SXin Li return false;
3655*67e74705SXin Li }
3656*67e74705SXin Li
3657*67e74705SXin Li namespace {
3658*67e74705SXin Li struct BaseAndFieldInfo {
3659*67e74705SXin Li Sema &S;
3660*67e74705SXin Li CXXConstructorDecl *Ctor;
3661*67e74705SXin Li bool AnyErrorsInInits;
3662*67e74705SXin Li ImplicitInitializerKind IIK;
3663*67e74705SXin Li llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3664*67e74705SXin Li SmallVector<CXXCtorInitializer*, 8> AllToInit;
3665*67e74705SXin Li llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3666*67e74705SXin Li
BaseAndFieldInfo__anon75252e180411::BaseAndFieldInfo3667*67e74705SXin Li BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3668*67e74705SXin Li : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3669*67e74705SXin Li bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3670*67e74705SXin Li if (Ctor->getInheritedConstructor())
3671*67e74705SXin Li IIK = IIK_Inherit;
3672*67e74705SXin Li else if (Generated && Ctor->isCopyConstructor())
3673*67e74705SXin Li IIK = IIK_Copy;
3674*67e74705SXin Li else if (Generated && Ctor->isMoveConstructor())
3675*67e74705SXin Li IIK = IIK_Move;
3676*67e74705SXin Li else
3677*67e74705SXin Li IIK = IIK_Default;
3678*67e74705SXin Li }
3679*67e74705SXin Li
isImplicitCopyOrMove__anon75252e180411::BaseAndFieldInfo3680*67e74705SXin Li bool isImplicitCopyOrMove() const {
3681*67e74705SXin Li switch (IIK) {
3682*67e74705SXin Li case IIK_Copy:
3683*67e74705SXin Li case IIK_Move:
3684*67e74705SXin Li return true;
3685*67e74705SXin Li
3686*67e74705SXin Li case IIK_Default:
3687*67e74705SXin Li case IIK_Inherit:
3688*67e74705SXin Li return false;
3689*67e74705SXin Li }
3690*67e74705SXin Li
3691*67e74705SXin Li llvm_unreachable("Invalid ImplicitInitializerKind!");
3692*67e74705SXin Li }
3693*67e74705SXin Li
addFieldInitializer__anon75252e180411::BaseAndFieldInfo3694*67e74705SXin Li bool addFieldInitializer(CXXCtorInitializer *Init) {
3695*67e74705SXin Li AllToInit.push_back(Init);
3696*67e74705SXin Li
3697*67e74705SXin Li // Check whether this initializer makes the field "used".
3698*67e74705SXin Li if (Init->getInit()->HasSideEffects(S.Context))
3699*67e74705SXin Li S.UnusedPrivateFields.remove(Init->getAnyMember());
3700*67e74705SXin Li
3701*67e74705SXin Li return false;
3702*67e74705SXin Li }
3703*67e74705SXin Li
isInactiveUnionMember__anon75252e180411::BaseAndFieldInfo3704*67e74705SXin Li bool isInactiveUnionMember(FieldDecl *Field) {
3705*67e74705SXin Li RecordDecl *Record = Field->getParent();
3706*67e74705SXin Li if (!Record->isUnion())
3707*67e74705SXin Li return false;
3708*67e74705SXin Li
3709*67e74705SXin Li if (FieldDecl *Active =
3710*67e74705SXin Li ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3711*67e74705SXin Li return Active != Field->getCanonicalDecl();
3712*67e74705SXin Li
3713*67e74705SXin Li // In an implicit copy or move constructor, ignore any in-class initializer.
3714*67e74705SXin Li if (isImplicitCopyOrMove())
3715*67e74705SXin Li return true;
3716*67e74705SXin Li
3717*67e74705SXin Li // If there's no explicit initialization, the field is active only if it
3718*67e74705SXin Li // has an in-class initializer...
3719*67e74705SXin Li if (Field->hasInClassInitializer())
3720*67e74705SXin Li return false;
3721*67e74705SXin Li // ... or it's an anonymous struct or union whose class has an in-class
3722*67e74705SXin Li // initializer.
3723*67e74705SXin Li if (!Field->isAnonymousStructOrUnion())
3724*67e74705SXin Li return true;
3725*67e74705SXin Li CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3726*67e74705SXin Li return !FieldRD->hasInClassInitializer();
3727*67e74705SXin Li }
3728*67e74705SXin Li
3729*67e74705SXin Li /// \brief Determine whether the given field is, or is within, a union member
3730*67e74705SXin Li /// that is inactive (because there was an initializer given for a different
3731*67e74705SXin Li /// member of the union, or because the union was not initialized at all).
isWithinInactiveUnionMember__anon75252e180411::BaseAndFieldInfo3732*67e74705SXin Li bool isWithinInactiveUnionMember(FieldDecl *Field,
3733*67e74705SXin Li IndirectFieldDecl *Indirect) {
3734*67e74705SXin Li if (!Indirect)
3735*67e74705SXin Li return isInactiveUnionMember(Field);
3736*67e74705SXin Li
3737*67e74705SXin Li for (auto *C : Indirect->chain()) {
3738*67e74705SXin Li FieldDecl *Field = dyn_cast<FieldDecl>(C);
3739*67e74705SXin Li if (Field && isInactiveUnionMember(Field))
3740*67e74705SXin Li return true;
3741*67e74705SXin Li }
3742*67e74705SXin Li return false;
3743*67e74705SXin Li }
3744*67e74705SXin Li };
3745*67e74705SXin Li }
3746*67e74705SXin Li
3747*67e74705SXin Li /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3748*67e74705SXin Li /// array type.
isIncompleteOrZeroLengthArrayType(ASTContext & Context,QualType T)3749*67e74705SXin Li static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3750*67e74705SXin Li if (T->isIncompleteArrayType())
3751*67e74705SXin Li return true;
3752*67e74705SXin Li
3753*67e74705SXin Li while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3754*67e74705SXin Li if (!ArrayT->getSize())
3755*67e74705SXin Li return true;
3756*67e74705SXin Li
3757*67e74705SXin Li T = ArrayT->getElementType();
3758*67e74705SXin Li }
3759*67e74705SXin Li
3760*67e74705SXin Li return false;
3761*67e74705SXin Li }
3762*67e74705SXin Li
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Field,IndirectFieldDecl * Indirect=nullptr)3763*67e74705SXin Li static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3764*67e74705SXin Li FieldDecl *Field,
3765*67e74705SXin Li IndirectFieldDecl *Indirect = nullptr) {
3766*67e74705SXin Li if (Field->isInvalidDecl())
3767*67e74705SXin Li return false;
3768*67e74705SXin Li
3769*67e74705SXin Li // Overwhelmingly common case: we have a direct initializer for this field.
3770*67e74705SXin Li if (CXXCtorInitializer *Init =
3771*67e74705SXin Li Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3772*67e74705SXin Li return Info.addFieldInitializer(Init);
3773*67e74705SXin Li
3774*67e74705SXin Li // C++11 [class.base.init]p8:
3775*67e74705SXin Li // if the entity is a non-static data member that has a
3776*67e74705SXin Li // brace-or-equal-initializer and either
3777*67e74705SXin Li // -- the constructor's class is a union and no other variant member of that
3778*67e74705SXin Li // union is designated by a mem-initializer-id or
3779*67e74705SXin Li // -- the constructor's class is not a union, and, if the entity is a member
3780*67e74705SXin Li // of an anonymous union, no other member of that union is designated by
3781*67e74705SXin Li // a mem-initializer-id,
3782*67e74705SXin Li // the entity is initialized as specified in [dcl.init].
3783*67e74705SXin Li //
3784*67e74705SXin Li // We also apply the same rules to handle anonymous structs within anonymous
3785*67e74705SXin Li // unions.
3786*67e74705SXin Li if (Info.isWithinInactiveUnionMember(Field, Indirect))
3787*67e74705SXin Li return false;
3788*67e74705SXin Li
3789*67e74705SXin Li if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3790*67e74705SXin Li ExprResult DIE =
3791*67e74705SXin Li SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3792*67e74705SXin Li if (DIE.isInvalid())
3793*67e74705SXin Li return true;
3794*67e74705SXin Li CXXCtorInitializer *Init;
3795*67e74705SXin Li if (Indirect)
3796*67e74705SXin Li Init = new (SemaRef.Context)
3797*67e74705SXin Li CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3798*67e74705SXin Li SourceLocation(), DIE.get(), SourceLocation());
3799*67e74705SXin Li else
3800*67e74705SXin Li Init = new (SemaRef.Context)
3801*67e74705SXin Li CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3802*67e74705SXin Li SourceLocation(), DIE.get(), SourceLocation());
3803*67e74705SXin Li return Info.addFieldInitializer(Init);
3804*67e74705SXin Li }
3805*67e74705SXin Li
3806*67e74705SXin Li // Don't initialize incomplete or zero-length arrays.
3807*67e74705SXin Li if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3808*67e74705SXin Li return false;
3809*67e74705SXin Li
3810*67e74705SXin Li // Don't try to build an implicit initializer if there were semantic
3811*67e74705SXin Li // errors in any of the initializers (and therefore we might be
3812*67e74705SXin Li // missing some that the user actually wrote).
3813*67e74705SXin Li if (Info.AnyErrorsInInits)
3814*67e74705SXin Li return false;
3815*67e74705SXin Li
3816*67e74705SXin Li CXXCtorInitializer *Init = nullptr;
3817*67e74705SXin Li if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3818*67e74705SXin Li Indirect, Init))
3819*67e74705SXin Li return true;
3820*67e74705SXin Li
3821*67e74705SXin Li if (!Init)
3822*67e74705SXin Li return false;
3823*67e74705SXin Li
3824*67e74705SXin Li return Info.addFieldInitializer(Init);
3825*67e74705SXin Li }
3826*67e74705SXin Li
3827*67e74705SXin Li bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)3828*67e74705SXin Li Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3829*67e74705SXin Li CXXCtorInitializer *Initializer) {
3830*67e74705SXin Li assert(Initializer->isDelegatingInitializer());
3831*67e74705SXin Li Constructor->setNumCtorInitializers(1);
3832*67e74705SXin Li CXXCtorInitializer **initializer =
3833*67e74705SXin Li new (Context) CXXCtorInitializer*[1];
3834*67e74705SXin Li memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3835*67e74705SXin Li Constructor->setCtorInitializers(initializer);
3836*67e74705SXin Li
3837*67e74705SXin Li if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3838*67e74705SXin Li MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3839*67e74705SXin Li DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3840*67e74705SXin Li }
3841*67e74705SXin Li
3842*67e74705SXin Li DelegatingCtorDecls.push_back(Constructor);
3843*67e74705SXin Li
3844*67e74705SXin Li DiagnoseUninitializedFields(*this, Constructor);
3845*67e74705SXin Li
3846*67e74705SXin Li return false;
3847*67e74705SXin Li }
3848*67e74705SXin Li
SetCtorInitializers(CXXConstructorDecl * Constructor,bool AnyErrors,ArrayRef<CXXCtorInitializer * > Initializers)3849*67e74705SXin Li bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3850*67e74705SXin Li ArrayRef<CXXCtorInitializer *> Initializers) {
3851*67e74705SXin Li if (Constructor->isDependentContext()) {
3852*67e74705SXin Li // Just store the initializers as written, they will be checked during
3853*67e74705SXin Li // instantiation.
3854*67e74705SXin Li if (!Initializers.empty()) {
3855*67e74705SXin Li Constructor->setNumCtorInitializers(Initializers.size());
3856*67e74705SXin Li CXXCtorInitializer **baseOrMemberInitializers =
3857*67e74705SXin Li new (Context) CXXCtorInitializer*[Initializers.size()];
3858*67e74705SXin Li memcpy(baseOrMemberInitializers, Initializers.data(),
3859*67e74705SXin Li Initializers.size() * sizeof(CXXCtorInitializer*));
3860*67e74705SXin Li Constructor->setCtorInitializers(baseOrMemberInitializers);
3861*67e74705SXin Li }
3862*67e74705SXin Li
3863*67e74705SXin Li // Let template instantiation know whether we had errors.
3864*67e74705SXin Li if (AnyErrors)
3865*67e74705SXin Li Constructor->setInvalidDecl();
3866*67e74705SXin Li
3867*67e74705SXin Li return false;
3868*67e74705SXin Li }
3869*67e74705SXin Li
3870*67e74705SXin Li BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3871*67e74705SXin Li
3872*67e74705SXin Li // We need to build the initializer AST according to order of construction
3873*67e74705SXin Li // and not what user specified in the Initializers list.
3874*67e74705SXin Li CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3875*67e74705SXin Li if (!ClassDecl)
3876*67e74705SXin Li return true;
3877*67e74705SXin Li
3878*67e74705SXin Li bool HadError = false;
3879*67e74705SXin Li
3880*67e74705SXin Li for (unsigned i = 0; i < Initializers.size(); i++) {
3881*67e74705SXin Li CXXCtorInitializer *Member = Initializers[i];
3882*67e74705SXin Li
3883*67e74705SXin Li if (Member->isBaseInitializer())
3884*67e74705SXin Li Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3885*67e74705SXin Li else {
3886*67e74705SXin Li Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3887*67e74705SXin Li
3888*67e74705SXin Li if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3889*67e74705SXin Li for (auto *C : F->chain()) {
3890*67e74705SXin Li FieldDecl *FD = dyn_cast<FieldDecl>(C);
3891*67e74705SXin Li if (FD && FD->getParent()->isUnion())
3892*67e74705SXin Li Info.ActiveUnionMember.insert(std::make_pair(
3893*67e74705SXin Li FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3894*67e74705SXin Li }
3895*67e74705SXin Li } else if (FieldDecl *FD = Member->getMember()) {
3896*67e74705SXin Li if (FD->getParent()->isUnion())
3897*67e74705SXin Li Info.ActiveUnionMember.insert(std::make_pair(
3898*67e74705SXin Li FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3899*67e74705SXin Li }
3900*67e74705SXin Li }
3901*67e74705SXin Li }
3902*67e74705SXin Li
3903*67e74705SXin Li // Keep track of the direct virtual bases.
3904*67e74705SXin Li llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3905*67e74705SXin Li for (auto &I : ClassDecl->bases()) {
3906*67e74705SXin Li if (I.isVirtual())
3907*67e74705SXin Li DirectVBases.insert(&I);
3908*67e74705SXin Li }
3909*67e74705SXin Li
3910*67e74705SXin Li // Push virtual bases before others.
3911*67e74705SXin Li for (auto &VBase : ClassDecl->vbases()) {
3912*67e74705SXin Li if (CXXCtorInitializer *Value
3913*67e74705SXin Li = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3914*67e74705SXin Li // [class.base.init]p7, per DR257:
3915*67e74705SXin Li // A mem-initializer where the mem-initializer-id names a virtual base
3916*67e74705SXin Li // class is ignored during execution of a constructor of any class that
3917*67e74705SXin Li // is not the most derived class.
3918*67e74705SXin Li if (ClassDecl->isAbstract()) {
3919*67e74705SXin Li // FIXME: Provide a fixit to remove the base specifier. This requires
3920*67e74705SXin Li // tracking the location of the associated comma for a base specifier.
3921*67e74705SXin Li Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3922*67e74705SXin Li << VBase.getType() << ClassDecl;
3923*67e74705SXin Li DiagnoseAbstractType(ClassDecl);
3924*67e74705SXin Li }
3925*67e74705SXin Li
3926*67e74705SXin Li Info.AllToInit.push_back(Value);
3927*67e74705SXin Li } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3928*67e74705SXin Li // [class.base.init]p8, per DR257:
3929*67e74705SXin Li // If a given [...] base class is not named by a mem-initializer-id
3930*67e74705SXin Li // [...] and the entity is not a virtual base class of an abstract
3931*67e74705SXin Li // class, then [...] the entity is default-initialized.
3932*67e74705SXin Li bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3933*67e74705SXin Li CXXCtorInitializer *CXXBaseInit;
3934*67e74705SXin Li if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3935*67e74705SXin Li &VBase, IsInheritedVirtualBase,
3936*67e74705SXin Li CXXBaseInit)) {
3937*67e74705SXin Li HadError = true;
3938*67e74705SXin Li continue;
3939*67e74705SXin Li }
3940*67e74705SXin Li
3941*67e74705SXin Li Info.AllToInit.push_back(CXXBaseInit);
3942*67e74705SXin Li }
3943*67e74705SXin Li }
3944*67e74705SXin Li
3945*67e74705SXin Li // Non-virtual bases.
3946*67e74705SXin Li for (auto &Base : ClassDecl->bases()) {
3947*67e74705SXin Li // Virtuals are in the virtual base list and already constructed.
3948*67e74705SXin Li if (Base.isVirtual())
3949*67e74705SXin Li continue;
3950*67e74705SXin Li
3951*67e74705SXin Li if (CXXCtorInitializer *Value
3952*67e74705SXin Li = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3953*67e74705SXin Li Info.AllToInit.push_back(Value);
3954*67e74705SXin Li } else if (!AnyErrors) {
3955*67e74705SXin Li CXXCtorInitializer *CXXBaseInit;
3956*67e74705SXin Li if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3957*67e74705SXin Li &Base, /*IsInheritedVirtualBase=*/false,
3958*67e74705SXin Li CXXBaseInit)) {
3959*67e74705SXin Li HadError = true;
3960*67e74705SXin Li continue;
3961*67e74705SXin Li }
3962*67e74705SXin Li
3963*67e74705SXin Li Info.AllToInit.push_back(CXXBaseInit);
3964*67e74705SXin Li }
3965*67e74705SXin Li }
3966*67e74705SXin Li
3967*67e74705SXin Li // Fields.
3968*67e74705SXin Li for (auto *Mem : ClassDecl->decls()) {
3969*67e74705SXin Li if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3970*67e74705SXin Li // C++ [class.bit]p2:
3971*67e74705SXin Li // A declaration for a bit-field that omits the identifier declares an
3972*67e74705SXin Li // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3973*67e74705SXin Li // initialized.
3974*67e74705SXin Li if (F->isUnnamedBitfield())
3975*67e74705SXin Li continue;
3976*67e74705SXin Li
3977*67e74705SXin Li // If we're not generating the implicit copy/move constructor, then we'll
3978*67e74705SXin Li // handle anonymous struct/union fields based on their individual
3979*67e74705SXin Li // indirect fields.
3980*67e74705SXin Li if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3981*67e74705SXin Li continue;
3982*67e74705SXin Li
3983*67e74705SXin Li if (CollectFieldInitializer(*this, Info, F))
3984*67e74705SXin Li HadError = true;
3985*67e74705SXin Li continue;
3986*67e74705SXin Li }
3987*67e74705SXin Li
3988*67e74705SXin Li // Beyond this point, we only consider default initialization.
3989*67e74705SXin Li if (Info.isImplicitCopyOrMove())
3990*67e74705SXin Li continue;
3991*67e74705SXin Li
3992*67e74705SXin Li if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3993*67e74705SXin Li if (F->getType()->isIncompleteArrayType()) {
3994*67e74705SXin Li assert(ClassDecl->hasFlexibleArrayMember() &&
3995*67e74705SXin Li "Incomplete array type is not valid");
3996*67e74705SXin Li continue;
3997*67e74705SXin Li }
3998*67e74705SXin Li
3999*67e74705SXin Li // Initialize each field of an anonymous struct individually.
4000*67e74705SXin Li if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4001*67e74705SXin Li HadError = true;
4002*67e74705SXin Li
4003*67e74705SXin Li continue;
4004*67e74705SXin Li }
4005*67e74705SXin Li }
4006*67e74705SXin Li
4007*67e74705SXin Li unsigned NumInitializers = Info.AllToInit.size();
4008*67e74705SXin Li if (NumInitializers > 0) {
4009*67e74705SXin Li Constructor->setNumCtorInitializers(NumInitializers);
4010*67e74705SXin Li CXXCtorInitializer **baseOrMemberInitializers =
4011*67e74705SXin Li new (Context) CXXCtorInitializer*[NumInitializers];
4012*67e74705SXin Li memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4013*67e74705SXin Li NumInitializers * sizeof(CXXCtorInitializer*));
4014*67e74705SXin Li Constructor->setCtorInitializers(baseOrMemberInitializers);
4015*67e74705SXin Li
4016*67e74705SXin Li // Constructors implicitly reference the base and member
4017*67e74705SXin Li // destructors.
4018*67e74705SXin Li MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4019*67e74705SXin Li Constructor->getParent());
4020*67e74705SXin Li }
4021*67e74705SXin Li
4022*67e74705SXin Li return HadError;
4023*67e74705SXin Li }
4024*67e74705SXin Li
PopulateKeysForFields(FieldDecl * Field,SmallVectorImpl<const void * > & IdealInits)4025*67e74705SXin Li static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4026*67e74705SXin Li if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4027*67e74705SXin Li const RecordDecl *RD = RT->getDecl();
4028*67e74705SXin Li if (RD->isAnonymousStructOrUnion()) {
4029*67e74705SXin Li for (auto *Field : RD->fields())
4030*67e74705SXin Li PopulateKeysForFields(Field, IdealInits);
4031*67e74705SXin Li return;
4032*67e74705SXin Li }
4033*67e74705SXin Li }
4034*67e74705SXin Li IdealInits.push_back(Field->getCanonicalDecl());
4035*67e74705SXin Li }
4036*67e74705SXin Li
GetKeyForBase(ASTContext & Context,QualType BaseType)4037*67e74705SXin Li static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4038*67e74705SXin Li return Context.getCanonicalType(BaseType).getTypePtr();
4039*67e74705SXin Li }
4040*67e74705SXin Li
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)4041*67e74705SXin Li static const void *GetKeyForMember(ASTContext &Context,
4042*67e74705SXin Li CXXCtorInitializer *Member) {
4043*67e74705SXin Li if (!Member->isAnyMemberInitializer())
4044*67e74705SXin Li return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4045*67e74705SXin Li
4046*67e74705SXin Li return Member->getAnyMember()->getCanonicalDecl();
4047*67e74705SXin Li }
4048*67e74705SXin Li
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,ArrayRef<CXXCtorInitializer * > Inits)4049*67e74705SXin Li static void DiagnoseBaseOrMemInitializerOrder(
4050*67e74705SXin Li Sema &SemaRef, const CXXConstructorDecl *Constructor,
4051*67e74705SXin Li ArrayRef<CXXCtorInitializer *> Inits) {
4052*67e74705SXin Li if (Constructor->getDeclContext()->isDependentContext())
4053*67e74705SXin Li return;
4054*67e74705SXin Li
4055*67e74705SXin Li // Don't check initializers order unless the warning is enabled at the
4056*67e74705SXin Li // location of at least one initializer.
4057*67e74705SXin Li bool ShouldCheckOrder = false;
4058*67e74705SXin Li for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4059*67e74705SXin Li CXXCtorInitializer *Init = Inits[InitIndex];
4060*67e74705SXin Li if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4061*67e74705SXin Li Init->getSourceLocation())) {
4062*67e74705SXin Li ShouldCheckOrder = true;
4063*67e74705SXin Li break;
4064*67e74705SXin Li }
4065*67e74705SXin Li }
4066*67e74705SXin Li if (!ShouldCheckOrder)
4067*67e74705SXin Li return;
4068*67e74705SXin Li
4069*67e74705SXin Li // Build the list of bases and members in the order that they'll
4070*67e74705SXin Li // actually be initialized. The explicit initializers should be in
4071*67e74705SXin Li // this same order but may be missing things.
4072*67e74705SXin Li SmallVector<const void*, 32> IdealInitKeys;
4073*67e74705SXin Li
4074*67e74705SXin Li const CXXRecordDecl *ClassDecl = Constructor->getParent();
4075*67e74705SXin Li
4076*67e74705SXin Li // 1. Virtual bases.
4077*67e74705SXin Li for (const auto &VBase : ClassDecl->vbases())
4078*67e74705SXin Li IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4079*67e74705SXin Li
4080*67e74705SXin Li // 2. Non-virtual bases.
4081*67e74705SXin Li for (const auto &Base : ClassDecl->bases()) {
4082*67e74705SXin Li if (Base.isVirtual())
4083*67e74705SXin Li continue;
4084*67e74705SXin Li IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4085*67e74705SXin Li }
4086*67e74705SXin Li
4087*67e74705SXin Li // 3. Direct fields.
4088*67e74705SXin Li for (auto *Field : ClassDecl->fields()) {
4089*67e74705SXin Li if (Field->isUnnamedBitfield())
4090*67e74705SXin Li continue;
4091*67e74705SXin Li
4092*67e74705SXin Li PopulateKeysForFields(Field, IdealInitKeys);
4093*67e74705SXin Li }
4094*67e74705SXin Li
4095*67e74705SXin Li unsigned NumIdealInits = IdealInitKeys.size();
4096*67e74705SXin Li unsigned IdealIndex = 0;
4097*67e74705SXin Li
4098*67e74705SXin Li CXXCtorInitializer *PrevInit = nullptr;
4099*67e74705SXin Li for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4100*67e74705SXin Li CXXCtorInitializer *Init = Inits[InitIndex];
4101*67e74705SXin Li const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4102*67e74705SXin Li
4103*67e74705SXin Li // Scan forward to try to find this initializer in the idealized
4104*67e74705SXin Li // initializers list.
4105*67e74705SXin Li for (; IdealIndex != NumIdealInits; ++IdealIndex)
4106*67e74705SXin Li if (InitKey == IdealInitKeys[IdealIndex])
4107*67e74705SXin Li break;
4108*67e74705SXin Li
4109*67e74705SXin Li // If we didn't find this initializer, it must be because we
4110*67e74705SXin Li // scanned past it on a previous iteration. That can only
4111*67e74705SXin Li // happen if we're out of order; emit a warning.
4112*67e74705SXin Li if (IdealIndex == NumIdealInits && PrevInit) {
4113*67e74705SXin Li Sema::SemaDiagnosticBuilder D =
4114*67e74705SXin Li SemaRef.Diag(PrevInit->getSourceLocation(),
4115*67e74705SXin Li diag::warn_initializer_out_of_order);
4116*67e74705SXin Li
4117*67e74705SXin Li if (PrevInit->isAnyMemberInitializer())
4118*67e74705SXin Li D << 0 << PrevInit->getAnyMember()->getDeclName();
4119*67e74705SXin Li else
4120*67e74705SXin Li D << 1 << PrevInit->getTypeSourceInfo()->getType();
4121*67e74705SXin Li
4122*67e74705SXin Li if (Init->isAnyMemberInitializer())
4123*67e74705SXin Li D << 0 << Init->getAnyMember()->getDeclName();
4124*67e74705SXin Li else
4125*67e74705SXin Li D << 1 << Init->getTypeSourceInfo()->getType();
4126*67e74705SXin Li
4127*67e74705SXin Li // Move back to the initializer's location in the ideal list.
4128*67e74705SXin Li for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4129*67e74705SXin Li if (InitKey == IdealInitKeys[IdealIndex])
4130*67e74705SXin Li break;
4131*67e74705SXin Li
4132*67e74705SXin Li assert(IdealIndex < NumIdealInits &&
4133*67e74705SXin Li "initializer not found in initializer list");
4134*67e74705SXin Li }
4135*67e74705SXin Li
4136*67e74705SXin Li PrevInit = Init;
4137*67e74705SXin Li }
4138*67e74705SXin Li }
4139*67e74705SXin Li
4140*67e74705SXin Li namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)4141*67e74705SXin Li bool CheckRedundantInit(Sema &S,
4142*67e74705SXin Li CXXCtorInitializer *Init,
4143*67e74705SXin Li CXXCtorInitializer *&PrevInit) {
4144*67e74705SXin Li if (!PrevInit) {
4145*67e74705SXin Li PrevInit = Init;
4146*67e74705SXin Li return false;
4147*67e74705SXin Li }
4148*67e74705SXin Li
4149*67e74705SXin Li if (FieldDecl *Field = Init->getAnyMember())
4150*67e74705SXin Li S.Diag(Init->getSourceLocation(),
4151*67e74705SXin Li diag::err_multiple_mem_initialization)
4152*67e74705SXin Li << Field->getDeclName()
4153*67e74705SXin Li << Init->getSourceRange();
4154*67e74705SXin Li else {
4155*67e74705SXin Li const Type *BaseClass = Init->getBaseClass();
4156*67e74705SXin Li assert(BaseClass && "neither field nor base");
4157*67e74705SXin Li S.Diag(Init->getSourceLocation(),
4158*67e74705SXin Li diag::err_multiple_base_initialization)
4159*67e74705SXin Li << QualType(BaseClass, 0)
4160*67e74705SXin Li << Init->getSourceRange();
4161*67e74705SXin Li }
4162*67e74705SXin Li S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4163*67e74705SXin Li << 0 << PrevInit->getSourceRange();
4164*67e74705SXin Li
4165*67e74705SXin Li return true;
4166*67e74705SXin Li }
4167*67e74705SXin Li
4168*67e74705SXin Li typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4169*67e74705SXin Li typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4170*67e74705SXin Li
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)4171*67e74705SXin Li bool CheckRedundantUnionInit(Sema &S,
4172*67e74705SXin Li CXXCtorInitializer *Init,
4173*67e74705SXin Li RedundantUnionMap &Unions) {
4174*67e74705SXin Li FieldDecl *Field = Init->getAnyMember();
4175*67e74705SXin Li RecordDecl *Parent = Field->getParent();
4176*67e74705SXin Li NamedDecl *Child = Field;
4177*67e74705SXin Li
4178*67e74705SXin Li while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4179*67e74705SXin Li if (Parent->isUnion()) {
4180*67e74705SXin Li UnionEntry &En = Unions[Parent];
4181*67e74705SXin Li if (En.first && En.first != Child) {
4182*67e74705SXin Li S.Diag(Init->getSourceLocation(),
4183*67e74705SXin Li diag::err_multiple_mem_union_initialization)
4184*67e74705SXin Li << Field->getDeclName()
4185*67e74705SXin Li << Init->getSourceRange();
4186*67e74705SXin Li S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4187*67e74705SXin Li << 0 << En.second->getSourceRange();
4188*67e74705SXin Li return true;
4189*67e74705SXin Li }
4190*67e74705SXin Li if (!En.first) {
4191*67e74705SXin Li En.first = Child;
4192*67e74705SXin Li En.second = Init;
4193*67e74705SXin Li }
4194*67e74705SXin Li if (!Parent->isAnonymousStructOrUnion())
4195*67e74705SXin Li return false;
4196*67e74705SXin Li }
4197*67e74705SXin Li
4198*67e74705SXin Li Child = Parent;
4199*67e74705SXin Li Parent = cast<RecordDecl>(Parent->getDeclContext());
4200*67e74705SXin Li }
4201*67e74705SXin Li
4202*67e74705SXin Li return false;
4203*67e74705SXin Li }
4204*67e74705SXin Li }
4205*67e74705SXin Li
4206*67e74705SXin Li /// ActOnMemInitializers - Handle the member initializers for a constructor.
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,ArrayRef<CXXCtorInitializer * > MemInits,bool AnyErrors)4207*67e74705SXin Li void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4208*67e74705SXin Li SourceLocation ColonLoc,
4209*67e74705SXin Li ArrayRef<CXXCtorInitializer*> MemInits,
4210*67e74705SXin Li bool AnyErrors) {
4211*67e74705SXin Li if (!ConstructorDecl)
4212*67e74705SXin Li return;
4213*67e74705SXin Li
4214*67e74705SXin Li AdjustDeclIfTemplate(ConstructorDecl);
4215*67e74705SXin Li
4216*67e74705SXin Li CXXConstructorDecl *Constructor
4217*67e74705SXin Li = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4218*67e74705SXin Li
4219*67e74705SXin Li if (!Constructor) {
4220*67e74705SXin Li Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4221*67e74705SXin Li return;
4222*67e74705SXin Li }
4223*67e74705SXin Li
4224*67e74705SXin Li // Mapping for the duplicate initializers check.
4225*67e74705SXin Li // For member initializers, this is keyed with a FieldDecl*.
4226*67e74705SXin Li // For base initializers, this is keyed with a Type*.
4227*67e74705SXin Li llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4228*67e74705SXin Li
4229*67e74705SXin Li // Mapping for the inconsistent anonymous-union initializers check.
4230*67e74705SXin Li RedundantUnionMap MemberUnions;
4231*67e74705SXin Li
4232*67e74705SXin Li bool HadError = false;
4233*67e74705SXin Li for (unsigned i = 0; i < MemInits.size(); i++) {
4234*67e74705SXin Li CXXCtorInitializer *Init = MemInits[i];
4235*67e74705SXin Li
4236*67e74705SXin Li // Set the source order index.
4237*67e74705SXin Li Init->setSourceOrder(i);
4238*67e74705SXin Li
4239*67e74705SXin Li if (Init->isAnyMemberInitializer()) {
4240*67e74705SXin Li const void *Key = GetKeyForMember(Context, Init);
4241*67e74705SXin Li if (CheckRedundantInit(*this, Init, Members[Key]) ||
4242*67e74705SXin Li CheckRedundantUnionInit(*this, Init, MemberUnions))
4243*67e74705SXin Li HadError = true;
4244*67e74705SXin Li } else if (Init->isBaseInitializer()) {
4245*67e74705SXin Li const void *Key = GetKeyForMember(Context, Init);
4246*67e74705SXin Li if (CheckRedundantInit(*this, Init, Members[Key]))
4247*67e74705SXin Li HadError = true;
4248*67e74705SXin Li } else {
4249*67e74705SXin Li assert(Init->isDelegatingInitializer());
4250*67e74705SXin Li // This must be the only initializer
4251*67e74705SXin Li if (MemInits.size() != 1) {
4252*67e74705SXin Li Diag(Init->getSourceLocation(),
4253*67e74705SXin Li diag::err_delegating_initializer_alone)
4254*67e74705SXin Li << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4255*67e74705SXin Li // We will treat this as being the only initializer.
4256*67e74705SXin Li }
4257*67e74705SXin Li SetDelegatingInitializer(Constructor, MemInits[i]);
4258*67e74705SXin Li // Return immediately as the initializer is set.
4259*67e74705SXin Li return;
4260*67e74705SXin Li }
4261*67e74705SXin Li }
4262*67e74705SXin Li
4263*67e74705SXin Li if (HadError)
4264*67e74705SXin Li return;
4265*67e74705SXin Li
4266*67e74705SXin Li DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4267*67e74705SXin Li
4268*67e74705SXin Li SetCtorInitializers(Constructor, AnyErrors, MemInits);
4269*67e74705SXin Li
4270*67e74705SXin Li DiagnoseUninitializedFields(*this, Constructor);
4271*67e74705SXin Li }
4272*67e74705SXin Li
4273*67e74705SXin Li void
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)4274*67e74705SXin Li Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4275*67e74705SXin Li CXXRecordDecl *ClassDecl) {
4276*67e74705SXin Li // Ignore dependent contexts. Also ignore unions, since their members never
4277*67e74705SXin Li // have destructors implicitly called.
4278*67e74705SXin Li if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4279*67e74705SXin Li return;
4280*67e74705SXin Li
4281*67e74705SXin Li // FIXME: all the access-control diagnostics are positioned on the
4282*67e74705SXin Li // field/base declaration. That's probably good; that said, the
4283*67e74705SXin Li // user might reasonably want to know why the destructor is being
4284*67e74705SXin Li // emitted, and we currently don't say.
4285*67e74705SXin Li
4286*67e74705SXin Li // Non-static data members.
4287*67e74705SXin Li for (auto *Field : ClassDecl->fields()) {
4288*67e74705SXin Li if (Field->isInvalidDecl())
4289*67e74705SXin Li continue;
4290*67e74705SXin Li
4291*67e74705SXin Li // Don't destroy incomplete or zero-length arrays.
4292*67e74705SXin Li if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4293*67e74705SXin Li continue;
4294*67e74705SXin Li
4295*67e74705SXin Li QualType FieldType = Context.getBaseElementType(Field->getType());
4296*67e74705SXin Li
4297*67e74705SXin Li const RecordType* RT = FieldType->getAs<RecordType>();
4298*67e74705SXin Li if (!RT)
4299*67e74705SXin Li continue;
4300*67e74705SXin Li
4301*67e74705SXin Li CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4302*67e74705SXin Li if (FieldClassDecl->isInvalidDecl())
4303*67e74705SXin Li continue;
4304*67e74705SXin Li if (FieldClassDecl->hasIrrelevantDestructor())
4305*67e74705SXin Li continue;
4306*67e74705SXin Li // The destructor for an implicit anonymous union member is never invoked.
4307*67e74705SXin Li if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4308*67e74705SXin Li continue;
4309*67e74705SXin Li
4310*67e74705SXin Li CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4311*67e74705SXin Li assert(Dtor && "No dtor found for FieldClassDecl!");
4312*67e74705SXin Li CheckDestructorAccess(Field->getLocation(), Dtor,
4313*67e74705SXin Li PDiag(diag::err_access_dtor_field)
4314*67e74705SXin Li << Field->getDeclName()
4315*67e74705SXin Li << FieldType);
4316*67e74705SXin Li
4317*67e74705SXin Li MarkFunctionReferenced(Location, Dtor);
4318*67e74705SXin Li DiagnoseUseOfDecl(Dtor, Location);
4319*67e74705SXin Li }
4320*67e74705SXin Li
4321*67e74705SXin Li llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4322*67e74705SXin Li
4323*67e74705SXin Li // Bases.
4324*67e74705SXin Li for (const auto &Base : ClassDecl->bases()) {
4325*67e74705SXin Li // Bases are always records in a well-formed non-dependent class.
4326*67e74705SXin Li const RecordType *RT = Base.getType()->getAs<RecordType>();
4327*67e74705SXin Li
4328*67e74705SXin Li // Remember direct virtual bases.
4329*67e74705SXin Li if (Base.isVirtual())
4330*67e74705SXin Li DirectVirtualBases.insert(RT);
4331*67e74705SXin Li
4332*67e74705SXin Li CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4333*67e74705SXin Li // If our base class is invalid, we probably can't get its dtor anyway.
4334*67e74705SXin Li if (BaseClassDecl->isInvalidDecl())
4335*67e74705SXin Li continue;
4336*67e74705SXin Li if (BaseClassDecl->hasIrrelevantDestructor())
4337*67e74705SXin Li continue;
4338*67e74705SXin Li
4339*67e74705SXin Li CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4340*67e74705SXin Li assert(Dtor && "No dtor found for BaseClassDecl!");
4341*67e74705SXin Li
4342*67e74705SXin Li // FIXME: caret should be on the start of the class name
4343*67e74705SXin Li CheckDestructorAccess(Base.getLocStart(), Dtor,
4344*67e74705SXin Li PDiag(diag::err_access_dtor_base)
4345*67e74705SXin Li << Base.getType()
4346*67e74705SXin Li << Base.getSourceRange(),
4347*67e74705SXin Li Context.getTypeDeclType(ClassDecl));
4348*67e74705SXin Li
4349*67e74705SXin Li MarkFunctionReferenced(Location, Dtor);
4350*67e74705SXin Li DiagnoseUseOfDecl(Dtor, Location);
4351*67e74705SXin Li }
4352*67e74705SXin Li
4353*67e74705SXin Li // Virtual bases.
4354*67e74705SXin Li for (const auto &VBase : ClassDecl->vbases()) {
4355*67e74705SXin Li // Bases are always records in a well-formed non-dependent class.
4356*67e74705SXin Li const RecordType *RT = VBase.getType()->castAs<RecordType>();
4357*67e74705SXin Li
4358*67e74705SXin Li // Ignore direct virtual bases.
4359*67e74705SXin Li if (DirectVirtualBases.count(RT))
4360*67e74705SXin Li continue;
4361*67e74705SXin Li
4362*67e74705SXin Li CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4363*67e74705SXin Li // If our base class is invalid, we probably can't get its dtor anyway.
4364*67e74705SXin Li if (BaseClassDecl->isInvalidDecl())
4365*67e74705SXin Li continue;
4366*67e74705SXin Li if (BaseClassDecl->hasIrrelevantDestructor())
4367*67e74705SXin Li continue;
4368*67e74705SXin Li
4369*67e74705SXin Li CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4370*67e74705SXin Li assert(Dtor && "No dtor found for BaseClassDecl!");
4371*67e74705SXin Li if (CheckDestructorAccess(
4372*67e74705SXin Li ClassDecl->getLocation(), Dtor,
4373*67e74705SXin Li PDiag(diag::err_access_dtor_vbase)
4374*67e74705SXin Li << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4375*67e74705SXin Li Context.getTypeDeclType(ClassDecl)) ==
4376*67e74705SXin Li AR_accessible) {
4377*67e74705SXin Li CheckDerivedToBaseConversion(
4378*67e74705SXin Li Context.getTypeDeclType(ClassDecl), VBase.getType(),
4379*67e74705SXin Li diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4380*67e74705SXin Li SourceRange(), DeclarationName(), nullptr);
4381*67e74705SXin Li }
4382*67e74705SXin Li
4383*67e74705SXin Li MarkFunctionReferenced(Location, Dtor);
4384*67e74705SXin Li DiagnoseUseOfDecl(Dtor, Location);
4385*67e74705SXin Li }
4386*67e74705SXin Li }
4387*67e74705SXin Li
ActOnDefaultCtorInitializers(Decl * CDtorDecl)4388*67e74705SXin Li void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4389*67e74705SXin Li if (!CDtorDecl)
4390*67e74705SXin Li return;
4391*67e74705SXin Li
4392*67e74705SXin Li if (CXXConstructorDecl *Constructor
4393*67e74705SXin Li = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4394*67e74705SXin Li SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4395*67e74705SXin Li DiagnoseUninitializedFields(*this, Constructor);
4396*67e74705SXin Li }
4397*67e74705SXin Li }
4398*67e74705SXin Li
isAbstractType(SourceLocation Loc,QualType T)4399*67e74705SXin Li bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
4400*67e74705SXin Li if (!getLangOpts().CPlusPlus)
4401*67e74705SXin Li return false;
4402*67e74705SXin Li
4403*67e74705SXin Li const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
4404*67e74705SXin Li if (!RD)
4405*67e74705SXin Li return false;
4406*67e74705SXin Li
4407*67e74705SXin Li // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
4408*67e74705SXin Li // class template specialization here, but doing so breaks a lot of code.
4409*67e74705SXin Li
4410*67e74705SXin Li // We can't answer whether something is abstract until it has a
4411*67e74705SXin Li // definition. If it's currently being defined, we'll walk back
4412*67e74705SXin Li // over all the declarations when we have a full definition.
4413*67e74705SXin Li const CXXRecordDecl *Def = RD->getDefinition();
4414*67e74705SXin Li if (!Def || Def->isBeingDefined())
4415*67e74705SXin Li return false;
4416*67e74705SXin Li
4417*67e74705SXin Li return RD->isAbstract();
4418*67e74705SXin Li }
4419*67e74705SXin Li
RequireNonAbstractType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)4420*67e74705SXin Li bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4421*67e74705SXin Li TypeDiagnoser &Diagnoser) {
4422*67e74705SXin Li if (!isAbstractType(Loc, T))
4423*67e74705SXin Li return false;
4424*67e74705SXin Li
4425*67e74705SXin Li T = Context.getBaseElementType(T);
4426*67e74705SXin Li Diagnoser.diagnose(*this, Loc, T);
4427*67e74705SXin Li DiagnoseAbstractType(T->getAsCXXRecordDecl());
4428*67e74705SXin Li return true;
4429*67e74705SXin Li }
4430*67e74705SXin Li
DiagnoseAbstractType(const CXXRecordDecl * RD)4431*67e74705SXin Li void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4432*67e74705SXin Li // Check if we've already emitted the list of pure virtual functions
4433*67e74705SXin Li // for this class.
4434*67e74705SXin Li if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4435*67e74705SXin Li return;
4436*67e74705SXin Li
4437*67e74705SXin Li // If the diagnostic is suppressed, don't emit the notes. We're only
4438*67e74705SXin Li // going to emit them once, so try to attach them to a diagnostic we're
4439*67e74705SXin Li // actually going to show.
4440*67e74705SXin Li if (Diags.isLastDiagnosticIgnored())
4441*67e74705SXin Li return;
4442*67e74705SXin Li
4443*67e74705SXin Li CXXFinalOverriderMap FinalOverriders;
4444*67e74705SXin Li RD->getFinalOverriders(FinalOverriders);
4445*67e74705SXin Li
4446*67e74705SXin Li // Keep a set of seen pure methods so we won't diagnose the same method
4447*67e74705SXin Li // more than once.
4448*67e74705SXin Li llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4449*67e74705SXin Li
4450*67e74705SXin Li for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4451*67e74705SXin Li MEnd = FinalOverriders.end();
4452*67e74705SXin Li M != MEnd;
4453*67e74705SXin Li ++M) {
4454*67e74705SXin Li for (OverridingMethods::iterator SO = M->second.begin(),
4455*67e74705SXin Li SOEnd = M->second.end();
4456*67e74705SXin Li SO != SOEnd; ++SO) {
4457*67e74705SXin Li // C++ [class.abstract]p4:
4458*67e74705SXin Li // A class is abstract if it contains or inherits at least one
4459*67e74705SXin Li // pure virtual function for which the final overrider is pure
4460*67e74705SXin Li // virtual.
4461*67e74705SXin Li
4462*67e74705SXin Li //
4463*67e74705SXin Li if (SO->second.size() != 1)
4464*67e74705SXin Li continue;
4465*67e74705SXin Li
4466*67e74705SXin Li if (!SO->second.front().Method->isPure())
4467*67e74705SXin Li continue;
4468*67e74705SXin Li
4469*67e74705SXin Li if (!SeenPureMethods.insert(SO->second.front().Method).second)
4470*67e74705SXin Li continue;
4471*67e74705SXin Li
4472*67e74705SXin Li Diag(SO->second.front().Method->getLocation(),
4473*67e74705SXin Li diag::note_pure_virtual_function)
4474*67e74705SXin Li << SO->second.front().Method->getDeclName() << RD->getDeclName();
4475*67e74705SXin Li }
4476*67e74705SXin Li }
4477*67e74705SXin Li
4478*67e74705SXin Li if (!PureVirtualClassDiagSet)
4479*67e74705SXin Li PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4480*67e74705SXin Li PureVirtualClassDiagSet->insert(RD);
4481*67e74705SXin Li }
4482*67e74705SXin Li
4483*67e74705SXin Li namespace {
4484*67e74705SXin Li struct AbstractUsageInfo {
4485*67e74705SXin Li Sema &S;
4486*67e74705SXin Li CXXRecordDecl *Record;
4487*67e74705SXin Li CanQualType AbstractType;
4488*67e74705SXin Li bool Invalid;
4489*67e74705SXin Li
AbstractUsageInfo__anon75252e180611::AbstractUsageInfo4490*67e74705SXin Li AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4491*67e74705SXin Li : S(S), Record(Record),
4492*67e74705SXin Li AbstractType(S.Context.getCanonicalType(
4493*67e74705SXin Li S.Context.getTypeDeclType(Record))),
4494*67e74705SXin Li Invalid(false) {}
4495*67e74705SXin Li
DiagnoseAbstractType__anon75252e180611::AbstractUsageInfo4496*67e74705SXin Li void DiagnoseAbstractType() {
4497*67e74705SXin Li if (Invalid) return;
4498*67e74705SXin Li S.DiagnoseAbstractType(Record);
4499*67e74705SXin Li Invalid = true;
4500*67e74705SXin Li }
4501*67e74705SXin Li
4502*67e74705SXin Li void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4503*67e74705SXin Li };
4504*67e74705SXin Li
4505*67e74705SXin Li struct CheckAbstractUsage {
4506*67e74705SXin Li AbstractUsageInfo &Info;
4507*67e74705SXin Li const NamedDecl *Ctx;
4508*67e74705SXin Li
CheckAbstractUsage__anon75252e180611::CheckAbstractUsage4509*67e74705SXin Li CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4510*67e74705SXin Li : Info(Info), Ctx(Ctx) {}
4511*67e74705SXin Li
Visit__anon75252e180611::CheckAbstractUsage4512*67e74705SXin Li void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4513*67e74705SXin Li switch (TL.getTypeLocClass()) {
4514*67e74705SXin Li #define ABSTRACT_TYPELOC(CLASS, PARENT)
4515*67e74705SXin Li #define TYPELOC(CLASS, PARENT) \
4516*67e74705SXin Li case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4517*67e74705SXin Li #include "clang/AST/TypeLocNodes.def"
4518*67e74705SXin Li }
4519*67e74705SXin Li }
4520*67e74705SXin Li
Check__anon75252e180611::CheckAbstractUsage4521*67e74705SXin Li void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4522*67e74705SXin Li Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4523*67e74705SXin Li for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4524*67e74705SXin Li if (!TL.getParam(I))
4525*67e74705SXin Li continue;
4526*67e74705SXin Li
4527*67e74705SXin Li TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4528*67e74705SXin Li if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4529*67e74705SXin Li }
4530*67e74705SXin Li }
4531*67e74705SXin Li
Check__anon75252e180611::CheckAbstractUsage4532*67e74705SXin Li void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4533*67e74705SXin Li Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4534*67e74705SXin Li }
4535*67e74705SXin Li
Check__anon75252e180611::CheckAbstractUsage4536*67e74705SXin Li void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4537*67e74705SXin Li // Visit the type parameters from a permissive context.
4538*67e74705SXin Li for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4539*67e74705SXin Li TemplateArgumentLoc TAL = TL.getArgLoc(I);
4540*67e74705SXin Li if (TAL.getArgument().getKind() == TemplateArgument::Type)
4541*67e74705SXin Li if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4542*67e74705SXin Li Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4543*67e74705SXin Li // TODO: other template argument types?
4544*67e74705SXin Li }
4545*67e74705SXin Li }
4546*67e74705SXin Li
4547*67e74705SXin Li // Visit pointee types from a permissive context.
4548*67e74705SXin Li #define CheckPolymorphic(Type) \
4549*67e74705SXin Li void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4550*67e74705SXin Li Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4551*67e74705SXin Li }
4552*67e74705SXin Li CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anon75252e180611::CheckAbstractUsage4553*67e74705SXin Li CheckPolymorphic(ReferenceTypeLoc)
4554*67e74705SXin Li CheckPolymorphic(MemberPointerTypeLoc)
4555*67e74705SXin Li CheckPolymorphic(BlockPointerTypeLoc)
4556*67e74705SXin Li CheckPolymorphic(AtomicTypeLoc)
4557*67e74705SXin Li
4558*67e74705SXin Li /// Handle all the types we haven't given a more specific
4559*67e74705SXin Li /// implementation for above.
4560*67e74705SXin Li void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4561*67e74705SXin Li // Every other kind of type that we haven't called out already
4562*67e74705SXin Li // that has an inner type is either (1) sugar or (2) contains that
4563*67e74705SXin Li // inner type in some way as a subobject.
4564*67e74705SXin Li if (TypeLoc Next = TL.getNextTypeLoc())
4565*67e74705SXin Li return Visit(Next, Sel);
4566*67e74705SXin Li
4567*67e74705SXin Li // If there's no inner type and we're in a permissive context,
4568*67e74705SXin Li // don't diagnose.
4569*67e74705SXin Li if (Sel == Sema::AbstractNone) return;
4570*67e74705SXin Li
4571*67e74705SXin Li // Check whether the type matches the abstract type.
4572*67e74705SXin Li QualType T = TL.getType();
4573*67e74705SXin Li if (T->isArrayType()) {
4574*67e74705SXin Li Sel = Sema::AbstractArrayType;
4575*67e74705SXin Li T = Info.S.Context.getBaseElementType(T);
4576*67e74705SXin Li }
4577*67e74705SXin Li CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4578*67e74705SXin Li if (CT != Info.AbstractType) return;
4579*67e74705SXin Li
4580*67e74705SXin Li // It matched; do some magic.
4581*67e74705SXin Li if (Sel == Sema::AbstractArrayType) {
4582*67e74705SXin Li Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4583*67e74705SXin Li << T << TL.getSourceRange();
4584*67e74705SXin Li } else {
4585*67e74705SXin Li Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4586*67e74705SXin Li << Sel << T << TL.getSourceRange();
4587*67e74705SXin Li }
4588*67e74705SXin Li Info.DiagnoseAbstractType();
4589*67e74705SXin Li }
4590*67e74705SXin Li };
4591*67e74705SXin Li
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)4592*67e74705SXin Li void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4593*67e74705SXin Li Sema::AbstractDiagSelID Sel) {
4594*67e74705SXin Li CheckAbstractUsage(*this, D).Visit(TL, Sel);
4595*67e74705SXin Li }
4596*67e74705SXin Li
4597*67e74705SXin Li }
4598*67e74705SXin Li
4599*67e74705SXin Li /// Check for invalid uses of an abstract type in a method declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXMethodDecl * MD)4600*67e74705SXin Li static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4601*67e74705SXin Li CXXMethodDecl *MD) {
4602*67e74705SXin Li // No need to do the check on definitions, which require that
4603*67e74705SXin Li // the return/param types be complete.
4604*67e74705SXin Li if (MD->doesThisDeclarationHaveABody())
4605*67e74705SXin Li return;
4606*67e74705SXin Li
4607*67e74705SXin Li // For safety's sake, just ignore it if we don't have type source
4608*67e74705SXin Li // information. This should never happen for non-implicit methods,
4609*67e74705SXin Li // but...
4610*67e74705SXin Li if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4611*67e74705SXin Li Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4612*67e74705SXin Li }
4613*67e74705SXin Li
4614*67e74705SXin Li /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)4615*67e74705SXin Li static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4616*67e74705SXin Li CXXRecordDecl *RD) {
4617*67e74705SXin Li for (auto *D : RD->decls()) {
4618*67e74705SXin Li if (D->isImplicit()) continue;
4619*67e74705SXin Li
4620*67e74705SXin Li // Methods and method templates.
4621*67e74705SXin Li if (isa<CXXMethodDecl>(D)) {
4622*67e74705SXin Li CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4623*67e74705SXin Li } else if (isa<FunctionTemplateDecl>(D)) {
4624*67e74705SXin Li FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4625*67e74705SXin Li CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4626*67e74705SXin Li
4627*67e74705SXin Li // Fields and static variables.
4628*67e74705SXin Li } else if (isa<FieldDecl>(D)) {
4629*67e74705SXin Li FieldDecl *FD = cast<FieldDecl>(D);
4630*67e74705SXin Li if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4631*67e74705SXin Li Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4632*67e74705SXin Li } else if (isa<VarDecl>(D)) {
4633*67e74705SXin Li VarDecl *VD = cast<VarDecl>(D);
4634*67e74705SXin Li if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4635*67e74705SXin Li Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4636*67e74705SXin Li
4637*67e74705SXin Li // Nested classes and class templates.
4638*67e74705SXin Li } else if (isa<CXXRecordDecl>(D)) {
4639*67e74705SXin Li CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4640*67e74705SXin Li } else if (isa<ClassTemplateDecl>(D)) {
4641*67e74705SXin Li CheckAbstractClassUsage(Info,
4642*67e74705SXin Li cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4643*67e74705SXin Li }
4644*67e74705SXin Li }
4645*67e74705SXin Li }
4646*67e74705SXin Li
ReferenceDllExportedMethods(Sema & S,CXXRecordDecl * Class)4647*67e74705SXin Li static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4648*67e74705SXin Li Attr *ClassAttr = getDLLAttr(Class);
4649*67e74705SXin Li if (!ClassAttr)
4650*67e74705SXin Li return;
4651*67e74705SXin Li
4652*67e74705SXin Li assert(ClassAttr->getKind() == attr::DLLExport);
4653*67e74705SXin Li
4654*67e74705SXin Li TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4655*67e74705SXin Li
4656*67e74705SXin Li if (TSK == TSK_ExplicitInstantiationDeclaration)
4657*67e74705SXin Li // Don't go any further if this is just an explicit instantiation
4658*67e74705SXin Li // declaration.
4659*67e74705SXin Li return;
4660*67e74705SXin Li
4661*67e74705SXin Li for (Decl *Member : Class->decls()) {
4662*67e74705SXin Li auto *MD = dyn_cast<CXXMethodDecl>(Member);
4663*67e74705SXin Li if (!MD)
4664*67e74705SXin Li continue;
4665*67e74705SXin Li
4666*67e74705SXin Li if (Member->getAttr<DLLExportAttr>()) {
4667*67e74705SXin Li if (MD->isUserProvided()) {
4668*67e74705SXin Li // Instantiate non-default class member functions ...
4669*67e74705SXin Li
4670*67e74705SXin Li // .. except for certain kinds of template specializations.
4671*67e74705SXin Li if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4672*67e74705SXin Li continue;
4673*67e74705SXin Li
4674*67e74705SXin Li S.MarkFunctionReferenced(Class->getLocation(), MD);
4675*67e74705SXin Li
4676*67e74705SXin Li // The function will be passed to the consumer when its definition is
4677*67e74705SXin Li // encountered.
4678*67e74705SXin Li } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4679*67e74705SXin Li MD->isCopyAssignmentOperator() ||
4680*67e74705SXin Li MD->isMoveAssignmentOperator()) {
4681*67e74705SXin Li // Synthesize and instantiate non-trivial implicit methods, explicitly
4682*67e74705SXin Li // defaulted methods, and the copy and move assignment operators. The
4683*67e74705SXin Li // latter are exported even if they are trivial, because the address of
4684*67e74705SXin Li // an operator can be taken and should compare equal accross libraries.
4685*67e74705SXin Li DiagnosticErrorTrap Trap(S.Diags);
4686*67e74705SXin Li S.MarkFunctionReferenced(Class->getLocation(), MD);
4687*67e74705SXin Li if (Trap.hasErrorOccurred()) {
4688*67e74705SXin Li S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4689*67e74705SXin Li << Class->getName() << !S.getLangOpts().CPlusPlus11;
4690*67e74705SXin Li break;
4691*67e74705SXin Li }
4692*67e74705SXin Li
4693*67e74705SXin Li // There is no later point when we will see the definition of this
4694*67e74705SXin Li // function, so pass it to the consumer now.
4695*67e74705SXin Li S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4696*67e74705SXin Li }
4697*67e74705SXin Li }
4698*67e74705SXin Li }
4699*67e74705SXin Li }
4700*67e74705SXin Li
4701*67e74705SXin Li /// \brief Check class-level dllimport/dllexport attribute.
checkClassLevelDLLAttribute(CXXRecordDecl * Class)4702*67e74705SXin Li void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4703*67e74705SXin Li Attr *ClassAttr = getDLLAttr(Class);
4704*67e74705SXin Li
4705*67e74705SXin Li // MSVC inherits DLL attributes to partial class template specializations.
4706*67e74705SXin Li if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4707*67e74705SXin Li if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4708*67e74705SXin Li if (Attr *TemplateAttr =
4709*67e74705SXin Li getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4710*67e74705SXin Li auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4711*67e74705SXin Li A->setInherited(true);
4712*67e74705SXin Li ClassAttr = A;
4713*67e74705SXin Li }
4714*67e74705SXin Li }
4715*67e74705SXin Li }
4716*67e74705SXin Li
4717*67e74705SXin Li if (!ClassAttr)
4718*67e74705SXin Li return;
4719*67e74705SXin Li
4720*67e74705SXin Li if (!Class->isExternallyVisible()) {
4721*67e74705SXin Li Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4722*67e74705SXin Li << Class << ClassAttr;
4723*67e74705SXin Li return;
4724*67e74705SXin Li }
4725*67e74705SXin Li
4726*67e74705SXin Li if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4727*67e74705SXin Li !ClassAttr->isInherited()) {
4728*67e74705SXin Li // Diagnose dll attributes on members of class with dll attribute.
4729*67e74705SXin Li for (Decl *Member : Class->decls()) {
4730*67e74705SXin Li if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4731*67e74705SXin Li continue;
4732*67e74705SXin Li InheritableAttr *MemberAttr = getDLLAttr(Member);
4733*67e74705SXin Li if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4734*67e74705SXin Li continue;
4735*67e74705SXin Li
4736*67e74705SXin Li Diag(MemberAttr->getLocation(),
4737*67e74705SXin Li diag::err_attribute_dll_member_of_dll_class)
4738*67e74705SXin Li << MemberAttr << ClassAttr;
4739*67e74705SXin Li Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4740*67e74705SXin Li Member->setInvalidDecl();
4741*67e74705SXin Li }
4742*67e74705SXin Li }
4743*67e74705SXin Li
4744*67e74705SXin Li if (Class->getDescribedClassTemplate())
4745*67e74705SXin Li // Don't inherit dll attribute until the template is instantiated.
4746*67e74705SXin Li return;
4747*67e74705SXin Li
4748*67e74705SXin Li // The class is either imported or exported.
4749*67e74705SXin Li const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4750*67e74705SXin Li
4751*67e74705SXin Li TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4752*67e74705SXin Li
4753*67e74705SXin Li // Ignore explicit dllexport on explicit class template instantiation declarations.
4754*67e74705SXin Li if (ClassExported && !ClassAttr->isInherited() &&
4755*67e74705SXin Li TSK == TSK_ExplicitInstantiationDeclaration) {
4756*67e74705SXin Li Class->dropAttr<DLLExportAttr>();
4757*67e74705SXin Li return;
4758*67e74705SXin Li }
4759*67e74705SXin Li
4760*67e74705SXin Li // Force declaration of implicit members so they can inherit the attribute.
4761*67e74705SXin Li ForceDeclarationOfImplicitMembers(Class);
4762*67e74705SXin Li
4763*67e74705SXin Li // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4764*67e74705SXin Li // seem to be true in practice?
4765*67e74705SXin Li
4766*67e74705SXin Li for (Decl *Member : Class->decls()) {
4767*67e74705SXin Li VarDecl *VD = dyn_cast<VarDecl>(Member);
4768*67e74705SXin Li CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4769*67e74705SXin Li
4770*67e74705SXin Li // Only methods and static fields inherit the attributes.
4771*67e74705SXin Li if (!VD && !MD)
4772*67e74705SXin Li continue;
4773*67e74705SXin Li
4774*67e74705SXin Li if (MD) {
4775*67e74705SXin Li // Don't process deleted methods.
4776*67e74705SXin Li if (MD->isDeleted())
4777*67e74705SXin Li continue;
4778*67e74705SXin Li
4779*67e74705SXin Li if (MD->isInlined()) {
4780*67e74705SXin Li // MinGW does not import or export inline methods.
4781*67e74705SXin Li if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4782*67e74705SXin Li continue;
4783*67e74705SXin Li
4784*67e74705SXin Li // MSVC versions before 2015 don't export the move assignment operators
4785*67e74705SXin Li // and move constructor, so don't attempt to import/export them if
4786*67e74705SXin Li // we have a definition.
4787*67e74705SXin Li auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
4788*67e74705SXin Li if ((MD->isMoveAssignmentOperator() ||
4789*67e74705SXin Li (Ctor && Ctor->isMoveConstructor())) &&
4790*67e74705SXin Li !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4791*67e74705SXin Li continue;
4792*67e74705SXin Li
4793*67e74705SXin Li // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
4794*67e74705SXin Li // operator is exported anyway.
4795*67e74705SXin Li if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
4796*67e74705SXin Li (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
4797*67e74705SXin Li continue;
4798*67e74705SXin Li }
4799*67e74705SXin Li }
4800*67e74705SXin Li
4801*67e74705SXin Li if (!cast<NamedDecl>(Member)->isExternallyVisible())
4802*67e74705SXin Li continue;
4803*67e74705SXin Li
4804*67e74705SXin Li if (!getDLLAttr(Member)) {
4805*67e74705SXin Li auto *NewAttr =
4806*67e74705SXin Li cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4807*67e74705SXin Li NewAttr->setInherited(true);
4808*67e74705SXin Li Member->addAttr(NewAttr);
4809*67e74705SXin Li }
4810*67e74705SXin Li }
4811*67e74705SXin Li
4812*67e74705SXin Li if (ClassExported)
4813*67e74705SXin Li DelayedDllExportClasses.push_back(Class);
4814*67e74705SXin Li }
4815*67e74705SXin Li
4816*67e74705SXin Li /// \brief Perform propagation of DLL attributes from a derived class to a
4817*67e74705SXin Li /// templated base class for MS compatibility.
propagateDLLAttrToBaseClassTemplate(CXXRecordDecl * Class,Attr * ClassAttr,ClassTemplateSpecializationDecl * BaseTemplateSpec,SourceLocation BaseLoc)4818*67e74705SXin Li void Sema::propagateDLLAttrToBaseClassTemplate(
4819*67e74705SXin Li CXXRecordDecl *Class, Attr *ClassAttr,
4820*67e74705SXin Li ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4821*67e74705SXin Li if (getDLLAttr(
4822*67e74705SXin Li BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4823*67e74705SXin Li // If the base class template has a DLL attribute, don't try to change it.
4824*67e74705SXin Li return;
4825*67e74705SXin Li }
4826*67e74705SXin Li
4827*67e74705SXin Li auto TSK = BaseTemplateSpec->getSpecializationKind();
4828*67e74705SXin Li if (!getDLLAttr(BaseTemplateSpec) &&
4829*67e74705SXin Li (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4830*67e74705SXin Li TSK == TSK_ImplicitInstantiation)) {
4831*67e74705SXin Li // The template hasn't been instantiated yet (or it has, but only as an
4832*67e74705SXin Li // explicit instantiation declaration or implicit instantiation, which means
4833*67e74705SXin Li // we haven't codegenned any members yet), so propagate the attribute.
4834*67e74705SXin Li auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4835*67e74705SXin Li NewAttr->setInherited(true);
4836*67e74705SXin Li BaseTemplateSpec->addAttr(NewAttr);
4837*67e74705SXin Li
4838*67e74705SXin Li // If the template is already instantiated, checkDLLAttributeRedeclaration()
4839*67e74705SXin Li // needs to be run again to work see the new attribute. Otherwise this will
4840*67e74705SXin Li // get run whenever the template is instantiated.
4841*67e74705SXin Li if (TSK != TSK_Undeclared)
4842*67e74705SXin Li checkClassLevelDLLAttribute(BaseTemplateSpec);
4843*67e74705SXin Li
4844*67e74705SXin Li return;
4845*67e74705SXin Li }
4846*67e74705SXin Li
4847*67e74705SXin Li if (getDLLAttr(BaseTemplateSpec)) {
4848*67e74705SXin Li // The template has already been specialized or instantiated with an
4849*67e74705SXin Li // attribute, explicitly or through propagation. We should not try to change
4850*67e74705SXin Li // it.
4851*67e74705SXin Li return;
4852*67e74705SXin Li }
4853*67e74705SXin Li
4854*67e74705SXin Li // The template was previously instantiated or explicitly specialized without
4855*67e74705SXin Li // a dll attribute, It's too late for us to add an attribute, so warn that
4856*67e74705SXin Li // this is unsupported.
4857*67e74705SXin Li Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4858*67e74705SXin Li << BaseTemplateSpec->isExplicitSpecialization();
4859*67e74705SXin Li Diag(ClassAttr->getLocation(), diag::note_attribute);
4860*67e74705SXin Li if (BaseTemplateSpec->isExplicitSpecialization()) {
4861*67e74705SXin Li Diag(BaseTemplateSpec->getLocation(),
4862*67e74705SXin Li diag::note_template_class_explicit_specialization_was_here)
4863*67e74705SXin Li << BaseTemplateSpec;
4864*67e74705SXin Li } else {
4865*67e74705SXin Li Diag(BaseTemplateSpec->getPointOfInstantiation(),
4866*67e74705SXin Li diag::note_template_class_instantiation_was_here)
4867*67e74705SXin Li << BaseTemplateSpec;
4868*67e74705SXin Li }
4869*67e74705SXin Li }
4870*67e74705SXin Li
DefineImplicitSpecialMember(Sema & S,CXXMethodDecl * MD,SourceLocation DefaultLoc)4871*67e74705SXin Li static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
4872*67e74705SXin Li SourceLocation DefaultLoc) {
4873*67e74705SXin Li switch (S.getSpecialMember(MD)) {
4874*67e74705SXin Li case Sema::CXXDefaultConstructor:
4875*67e74705SXin Li S.DefineImplicitDefaultConstructor(DefaultLoc,
4876*67e74705SXin Li cast<CXXConstructorDecl>(MD));
4877*67e74705SXin Li break;
4878*67e74705SXin Li case Sema::CXXCopyConstructor:
4879*67e74705SXin Li S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
4880*67e74705SXin Li break;
4881*67e74705SXin Li case Sema::CXXCopyAssignment:
4882*67e74705SXin Li S.DefineImplicitCopyAssignment(DefaultLoc, MD);
4883*67e74705SXin Li break;
4884*67e74705SXin Li case Sema::CXXDestructor:
4885*67e74705SXin Li S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
4886*67e74705SXin Li break;
4887*67e74705SXin Li case Sema::CXXMoveConstructor:
4888*67e74705SXin Li S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
4889*67e74705SXin Li break;
4890*67e74705SXin Li case Sema::CXXMoveAssignment:
4891*67e74705SXin Li S.DefineImplicitMoveAssignment(DefaultLoc, MD);
4892*67e74705SXin Li break;
4893*67e74705SXin Li case Sema::CXXInvalid:
4894*67e74705SXin Li llvm_unreachable("Invalid special member.");
4895*67e74705SXin Li }
4896*67e74705SXin Li }
4897*67e74705SXin Li
4898*67e74705SXin Li /// \brief Perform semantic checks on a class definition that has been
4899*67e74705SXin Li /// completing, introducing implicitly-declared members, checking for
4900*67e74705SXin Li /// abstract types, etc.
CheckCompletedCXXClass(CXXRecordDecl * Record)4901*67e74705SXin Li void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4902*67e74705SXin Li if (!Record)
4903*67e74705SXin Li return;
4904*67e74705SXin Li
4905*67e74705SXin Li if (Record->isAbstract() && !Record->isInvalidDecl()) {
4906*67e74705SXin Li AbstractUsageInfo Info(*this, Record);
4907*67e74705SXin Li CheckAbstractClassUsage(Info, Record);
4908*67e74705SXin Li }
4909*67e74705SXin Li
4910*67e74705SXin Li // If this is not an aggregate type and has no user-declared constructor,
4911*67e74705SXin Li // complain about any non-static data members of reference or const scalar
4912*67e74705SXin Li // type, since they will never get initializers.
4913*67e74705SXin Li if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4914*67e74705SXin Li !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4915*67e74705SXin Li !Record->isLambda()) {
4916*67e74705SXin Li bool Complained = false;
4917*67e74705SXin Li for (const auto *F : Record->fields()) {
4918*67e74705SXin Li if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4919*67e74705SXin Li continue;
4920*67e74705SXin Li
4921*67e74705SXin Li if (F->getType()->isReferenceType() ||
4922*67e74705SXin Li (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4923*67e74705SXin Li if (!Complained) {
4924*67e74705SXin Li Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4925*67e74705SXin Li << Record->getTagKind() << Record;
4926*67e74705SXin Li Complained = true;
4927*67e74705SXin Li }
4928*67e74705SXin Li
4929*67e74705SXin Li Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4930*67e74705SXin Li << F->getType()->isReferenceType()
4931*67e74705SXin Li << F->getDeclName();
4932*67e74705SXin Li }
4933*67e74705SXin Li }
4934*67e74705SXin Li }
4935*67e74705SXin Li
4936*67e74705SXin Li if (Record->getIdentifier()) {
4937*67e74705SXin Li // C++ [class.mem]p13:
4938*67e74705SXin Li // If T is the name of a class, then each of the following shall have a
4939*67e74705SXin Li // name different from T:
4940*67e74705SXin Li // - every member of every anonymous union that is a member of class T.
4941*67e74705SXin Li //
4942*67e74705SXin Li // C++ [class.mem]p14:
4943*67e74705SXin Li // In addition, if class T has a user-declared constructor (12.1), every
4944*67e74705SXin Li // non-static data member of class T shall have a name different from T.
4945*67e74705SXin Li DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4946*67e74705SXin Li for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4947*67e74705SXin Li ++I) {
4948*67e74705SXin Li NamedDecl *D = *I;
4949*67e74705SXin Li if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4950*67e74705SXin Li isa<IndirectFieldDecl>(D)) {
4951*67e74705SXin Li Diag(D->getLocation(), diag::err_member_name_of_class)
4952*67e74705SXin Li << D->getDeclName();
4953*67e74705SXin Li break;
4954*67e74705SXin Li }
4955*67e74705SXin Li }
4956*67e74705SXin Li }
4957*67e74705SXin Li
4958*67e74705SXin Li // Warn if the class has virtual methods but non-virtual public destructor.
4959*67e74705SXin Li if (Record->isPolymorphic() && !Record->isDependentType()) {
4960*67e74705SXin Li CXXDestructorDecl *dtor = Record->getDestructor();
4961*67e74705SXin Li if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4962*67e74705SXin Li !Record->hasAttr<FinalAttr>())
4963*67e74705SXin Li Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4964*67e74705SXin Li diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4965*67e74705SXin Li }
4966*67e74705SXin Li
4967*67e74705SXin Li if (Record->isAbstract()) {
4968*67e74705SXin Li if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4969*67e74705SXin Li Diag(Record->getLocation(), diag::warn_abstract_final_class)
4970*67e74705SXin Li << FA->isSpelledAsSealed();
4971*67e74705SXin Li DiagnoseAbstractType(Record);
4972*67e74705SXin Li }
4973*67e74705SXin Li }
4974*67e74705SXin Li
4975*67e74705SXin Li bool HasMethodWithOverrideControl = false,
4976*67e74705SXin Li HasOverridingMethodWithoutOverrideControl = false;
4977*67e74705SXin Li if (!Record->isDependentType()) {
4978*67e74705SXin Li for (auto *M : Record->methods()) {
4979*67e74705SXin Li // See if a method overloads virtual methods in a base
4980*67e74705SXin Li // class without overriding any.
4981*67e74705SXin Li if (!M->isStatic())
4982*67e74705SXin Li DiagnoseHiddenVirtualMethods(M);
4983*67e74705SXin Li if (M->hasAttr<OverrideAttr>())
4984*67e74705SXin Li HasMethodWithOverrideControl = true;
4985*67e74705SXin Li else if (M->size_overridden_methods() > 0)
4986*67e74705SXin Li HasOverridingMethodWithoutOverrideControl = true;
4987*67e74705SXin Li // Check whether the explicitly-defaulted special members are valid.
4988*67e74705SXin Li if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4989*67e74705SXin Li CheckExplicitlyDefaultedSpecialMember(M);
4990*67e74705SXin Li
4991*67e74705SXin Li // For an explicitly defaulted or deleted special member, we defer
4992*67e74705SXin Li // determining triviality until the class is complete. That time is now!
4993*67e74705SXin Li CXXSpecialMember CSM = getSpecialMember(M);
4994*67e74705SXin Li if (!M->isImplicit() && !M->isUserProvided()) {
4995*67e74705SXin Li if (CSM != CXXInvalid) {
4996*67e74705SXin Li M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4997*67e74705SXin Li
4998*67e74705SXin Li // Inform the class that we've finished declaring this member.
4999*67e74705SXin Li Record->finishedDefaultedOrDeletedMember(M);
5000*67e74705SXin Li }
5001*67e74705SXin Li }
5002*67e74705SXin Li
5003*67e74705SXin Li if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5004*67e74705SXin Li M->hasAttr<DLLExportAttr>()) {
5005*67e74705SXin Li if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5006*67e74705SXin Li M->isTrivial() &&
5007*67e74705SXin Li (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5008*67e74705SXin Li CSM == CXXDestructor))
5009*67e74705SXin Li M->dropAttr<DLLExportAttr>();
5010*67e74705SXin Li
5011*67e74705SXin Li if (M->hasAttr<DLLExportAttr>()) {
5012*67e74705SXin Li DefineImplicitSpecialMember(*this, M, M->getLocation());
5013*67e74705SXin Li ActOnFinishInlineFunctionDef(M);
5014*67e74705SXin Li }
5015*67e74705SXin Li }
5016*67e74705SXin Li }
5017*67e74705SXin Li }
5018*67e74705SXin Li
5019*67e74705SXin Li if (HasMethodWithOverrideControl &&
5020*67e74705SXin Li HasOverridingMethodWithoutOverrideControl) {
5021*67e74705SXin Li // At least one method has the 'override' control declared.
5022*67e74705SXin Li // Diagnose all other overridden methods which do not have 'override' specified on them.
5023*67e74705SXin Li for (auto *M : Record->methods())
5024*67e74705SXin Li DiagnoseAbsenceOfOverrideControl(M);
5025*67e74705SXin Li }
5026*67e74705SXin Li
5027*67e74705SXin Li // ms_struct is a request to use the same ABI rules as MSVC. Check
5028*67e74705SXin Li // whether this class uses any C++ features that are implemented
5029*67e74705SXin Li // completely differently in MSVC, and if so, emit a diagnostic.
5030*67e74705SXin Li // That diagnostic defaults to an error, but we allow projects to
5031*67e74705SXin Li // map it down to a warning (or ignore it). It's a fairly common
5032*67e74705SXin Li // practice among users of the ms_struct pragma to mass-annotate
5033*67e74705SXin Li // headers, sweeping up a bunch of types that the project doesn't
5034*67e74705SXin Li // really rely on MSVC-compatible layout for. We must therefore
5035*67e74705SXin Li // support "ms_struct except for C++ stuff" as a secondary ABI.
5036*67e74705SXin Li if (Record->isMsStruct(Context) &&
5037*67e74705SXin Li (Record->isPolymorphic() || Record->getNumBases())) {
5038*67e74705SXin Li Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5039*67e74705SXin Li }
5040*67e74705SXin Li
5041*67e74705SXin Li checkClassLevelDLLAttribute(Record);
5042*67e74705SXin Li }
5043*67e74705SXin Li
5044*67e74705SXin Li /// Look up the special member function that would be called by a special
5045*67e74705SXin Li /// member function for a subobject of class type.
5046*67e74705SXin Li ///
5047*67e74705SXin Li /// \param Class The class type of the subobject.
5048*67e74705SXin Li /// \param CSM The kind of special member function.
5049*67e74705SXin Li /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5050*67e74705SXin Li /// \param ConstRHS True if this is a copy operation with a const object
5051*67e74705SXin Li /// on its RHS, that is, if the argument to the outer special member
5052*67e74705SXin Li /// function is 'const' and this is not a field marked 'mutable'.
lookupCallFromSpecialMember(Sema & S,CXXRecordDecl * Class,Sema::CXXSpecialMember CSM,unsigned FieldQuals,bool ConstRHS)5053*67e74705SXin Li static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5054*67e74705SXin Li Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5055*67e74705SXin Li unsigned FieldQuals, bool ConstRHS) {
5056*67e74705SXin Li unsigned LHSQuals = 0;
5057*67e74705SXin Li if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5058*67e74705SXin Li LHSQuals = FieldQuals;
5059*67e74705SXin Li
5060*67e74705SXin Li unsigned RHSQuals = FieldQuals;
5061*67e74705SXin Li if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5062*67e74705SXin Li RHSQuals = 0;
5063*67e74705SXin Li else if (ConstRHS)
5064*67e74705SXin Li RHSQuals |= Qualifiers::Const;
5065*67e74705SXin Li
5066*67e74705SXin Li return S.LookupSpecialMember(Class, CSM,
5067*67e74705SXin Li RHSQuals & Qualifiers::Const,
5068*67e74705SXin Li RHSQuals & Qualifiers::Volatile,
5069*67e74705SXin Li false,
5070*67e74705SXin Li LHSQuals & Qualifiers::Const,
5071*67e74705SXin Li LHSQuals & Qualifiers::Volatile);
5072*67e74705SXin Li }
5073*67e74705SXin Li
5074*67e74705SXin Li class Sema::InheritedConstructorInfo {
5075*67e74705SXin Li Sema &S;
5076*67e74705SXin Li SourceLocation UseLoc;
5077*67e74705SXin Li
5078*67e74705SXin Li /// A mapping from the base classes through which the constructor was
5079*67e74705SXin Li /// inherited to the using shadow declaration in that base class (or a null
5080*67e74705SXin Li /// pointer if the constructor was declared in that base class).
5081*67e74705SXin Li llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5082*67e74705SXin Li InheritedFromBases;
5083*67e74705SXin Li
5084*67e74705SXin Li public:
InheritedConstructorInfo(Sema & S,SourceLocation UseLoc,ConstructorUsingShadowDecl * Shadow)5085*67e74705SXin Li InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5086*67e74705SXin Li ConstructorUsingShadowDecl *Shadow)
5087*67e74705SXin Li : S(S), UseLoc(UseLoc) {
5088*67e74705SXin Li bool DiagnosedMultipleConstructedBases = false;
5089*67e74705SXin Li CXXRecordDecl *ConstructedBase = nullptr;
5090*67e74705SXin Li UsingDecl *ConstructedBaseUsing = nullptr;
5091*67e74705SXin Li
5092*67e74705SXin Li // Find the set of such base class subobjects and check that there's a
5093*67e74705SXin Li // unique constructed subobject.
5094*67e74705SXin Li for (auto *D : Shadow->redecls()) {
5095*67e74705SXin Li auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5096*67e74705SXin Li auto *DNominatedBase = DShadow->getNominatedBaseClass();
5097*67e74705SXin Li auto *DConstructedBase = DShadow->getConstructedBaseClass();
5098*67e74705SXin Li
5099*67e74705SXin Li InheritedFromBases.insert(
5100*67e74705SXin Li std::make_pair(DNominatedBase->getCanonicalDecl(),
5101*67e74705SXin Li DShadow->getNominatedBaseClassShadowDecl()));
5102*67e74705SXin Li if (DShadow->constructsVirtualBase())
5103*67e74705SXin Li InheritedFromBases.insert(
5104*67e74705SXin Li std::make_pair(DConstructedBase->getCanonicalDecl(),
5105*67e74705SXin Li DShadow->getConstructedBaseClassShadowDecl()));
5106*67e74705SXin Li else
5107*67e74705SXin Li assert(DNominatedBase == DConstructedBase);
5108*67e74705SXin Li
5109*67e74705SXin Li // [class.inhctor.init]p2:
5110*67e74705SXin Li // If the constructor was inherited from multiple base class subobjects
5111*67e74705SXin Li // of type B, the program is ill-formed.
5112*67e74705SXin Li if (!ConstructedBase) {
5113*67e74705SXin Li ConstructedBase = DConstructedBase;
5114*67e74705SXin Li ConstructedBaseUsing = D->getUsingDecl();
5115*67e74705SXin Li } else if (ConstructedBase != DConstructedBase &&
5116*67e74705SXin Li !Shadow->isInvalidDecl()) {
5117*67e74705SXin Li if (!DiagnosedMultipleConstructedBases) {
5118*67e74705SXin Li S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5119*67e74705SXin Li << Shadow->getTargetDecl();
5120*67e74705SXin Li S.Diag(ConstructedBaseUsing->getLocation(),
5121*67e74705SXin Li diag::note_ambiguous_inherited_constructor_using)
5122*67e74705SXin Li << ConstructedBase;
5123*67e74705SXin Li DiagnosedMultipleConstructedBases = true;
5124*67e74705SXin Li }
5125*67e74705SXin Li S.Diag(D->getUsingDecl()->getLocation(),
5126*67e74705SXin Li diag::note_ambiguous_inherited_constructor_using)
5127*67e74705SXin Li << DConstructedBase;
5128*67e74705SXin Li }
5129*67e74705SXin Li }
5130*67e74705SXin Li
5131*67e74705SXin Li if (DiagnosedMultipleConstructedBases)
5132*67e74705SXin Li Shadow->setInvalidDecl();
5133*67e74705SXin Li }
5134*67e74705SXin Li
5135*67e74705SXin Li /// Find the constructor to use for inherited construction of a base class,
5136*67e74705SXin Li /// and whether that base class constructor inherits the constructor from a
5137*67e74705SXin Li /// virtual base class (in which case it won't actually invoke it).
5138*67e74705SXin Li std::pair<CXXConstructorDecl *, bool>
findConstructorForBase(CXXRecordDecl * Base,CXXConstructorDecl * Ctor) const5139*67e74705SXin Li findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5140*67e74705SXin Li auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5141*67e74705SXin Li if (It == InheritedFromBases.end())
5142*67e74705SXin Li return std::make_pair(nullptr, false);
5143*67e74705SXin Li
5144*67e74705SXin Li // This is an intermediary class.
5145*67e74705SXin Li if (It->second)
5146*67e74705SXin Li return std::make_pair(
5147*67e74705SXin Li S.findInheritingConstructor(UseLoc, Ctor, It->second),
5148*67e74705SXin Li It->second->constructsVirtualBase());
5149*67e74705SXin Li
5150*67e74705SXin Li // This is the base class from which the constructor was inherited.
5151*67e74705SXin Li return std::make_pair(Ctor, false);
5152*67e74705SXin Li }
5153*67e74705SXin Li };
5154*67e74705SXin Li
5155*67e74705SXin Li /// Is the special member function which would be selected to perform the
5156*67e74705SXin Li /// specified operation on the specified class type a constexpr constructor?
5157*67e74705SXin Li static bool
specialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)5158*67e74705SXin Li specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5159*67e74705SXin Li Sema::CXXSpecialMember CSM, unsigned Quals,
5160*67e74705SXin Li bool ConstRHS,
5161*67e74705SXin Li CXXConstructorDecl *InheritedCtor = nullptr,
5162*67e74705SXin Li Sema::InheritedConstructorInfo *Inherited = nullptr) {
5163*67e74705SXin Li // If we're inheriting a constructor, see if we need to call it for this base
5164*67e74705SXin Li // class.
5165*67e74705SXin Li if (InheritedCtor) {
5166*67e74705SXin Li assert(CSM == Sema::CXXDefaultConstructor);
5167*67e74705SXin Li auto BaseCtor =
5168*67e74705SXin Li Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5169*67e74705SXin Li if (BaseCtor)
5170*67e74705SXin Li return BaseCtor->isConstexpr();
5171*67e74705SXin Li }
5172*67e74705SXin Li
5173*67e74705SXin Li if (CSM == Sema::CXXDefaultConstructor)
5174*67e74705SXin Li return ClassDecl->hasConstexprDefaultConstructor();
5175*67e74705SXin Li
5176*67e74705SXin Li Sema::SpecialMemberOverloadResult *SMOR =
5177*67e74705SXin Li lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5178*67e74705SXin Li if (!SMOR || !SMOR->getMethod())
5179*67e74705SXin Li // A constructor we wouldn't select can't be "involved in initializing"
5180*67e74705SXin Li // anything.
5181*67e74705SXin Li return true;
5182*67e74705SXin Li return SMOR->getMethod()->isConstexpr();
5183*67e74705SXin Li }
5184*67e74705SXin Li
5185*67e74705SXin Li /// Determine whether the specified special member function would be constexpr
5186*67e74705SXin Li /// if it were implicitly defined.
defaultedSpecialMemberIsConstexpr(Sema & S,CXXRecordDecl * ClassDecl,Sema::CXXSpecialMember CSM,bool ConstArg,CXXConstructorDecl * InheritedCtor=nullptr,Sema::InheritedConstructorInfo * Inherited=nullptr)5187*67e74705SXin Li static bool defaultedSpecialMemberIsConstexpr(
5188*67e74705SXin Li Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5189*67e74705SXin Li bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5190*67e74705SXin Li Sema::InheritedConstructorInfo *Inherited = nullptr) {
5191*67e74705SXin Li if (!S.getLangOpts().CPlusPlus11)
5192*67e74705SXin Li return false;
5193*67e74705SXin Li
5194*67e74705SXin Li // C++11 [dcl.constexpr]p4:
5195*67e74705SXin Li // In the definition of a constexpr constructor [...]
5196*67e74705SXin Li bool Ctor = true;
5197*67e74705SXin Li switch (CSM) {
5198*67e74705SXin Li case Sema::CXXDefaultConstructor:
5199*67e74705SXin Li if (Inherited)
5200*67e74705SXin Li break;
5201*67e74705SXin Li // Since default constructor lookup is essentially trivial (and cannot
5202*67e74705SXin Li // involve, for instance, template instantiation), we compute whether a
5203*67e74705SXin Li // defaulted default constructor is constexpr directly within CXXRecordDecl.
5204*67e74705SXin Li //
5205*67e74705SXin Li // This is important for performance; we need to know whether the default
5206*67e74705SXin Li // constructor is constexpr to determine whether the type is a literal type.
5207*67e74705SXin Li return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5208*67e74705SXin Li
5209*67e74705SXin Li case Sema::CXXCopyConstructor:
5210*67e74705SXin Li case Sema::CXXMoveConstructor:
5211*67e74705SXin Li // For copy or move constructors, we need to perform overload resolution.
5212*67e74705SXin Li break;
5213*67e74705SXin Li
5214*67e74705SXin Li case Sema::CXXCopyAssignment:
5215*67e74705SXin Li case Sema::CXXMoveAssignment:
5216*67e74705SXin Li if (!S.getLangOpts().CPlusPlus14)
5217*67e74705SXin Li return false;
5218*67e74705SXin Li // In C++1y, we need to perform overload resolution.
5219*67e74705SXin Li Ctor = false;
5220*67e74705SXin Li break;
5221*67e74705SXin Li
5222*67e74705SXin Li case Sema::CXXDestructor:
5223*67e74705SXin Li case Sema::CXXInvalid:
5224*67e74705SXin Li return false;
5225*67e74705SXin Li }
5226*67e74705SXin Li
5227*67e74705SXin Li // -- if the class is a non-empty union, or for each non-empty anonymous
5228*67e74705SXin Li // union member of a non-union class, exactly one non-static data member
5229*67e74705SXin Li // shall be initialized; [DR1359]
5230*67e74705SXin Li //
5231*67e74705SXin Li // If we squint, this is guaranteed, since exactly one non-static data member
5232*67e74705SXin Li // will be initialized (if the constructor isn't deleted), we just don't know
5233*67e74705SXin Li // which one.
5234*67e74705SXin Li if (Ctor && ClassDecl->isUnion())
5235*67e74705SXin Li return CSM == Sema::CXXDefaultConstructor
5236*67e74705SXin Li ? ClassDecl->hasInClassInitializer() ||
5237*67e74705SXin Li !ClassDecl->hasVariantMembers()
5238*67e74705SXin Li : true;
5239*67e74705SXin Li
5240*67e74705SXin Li // -- the class shall not have any virtual base classes;
5241*67e74705SXin Li if (Ctor && ClassDecl->getNumVBases())
5242*67e74705SXin Li return false;
5243*67e74705SXin Li
5244*67e74705SXin Li // C++1y [class.copy]p26:
5245*67e74705SXin Li // -- [the class] is a literal type, and
5246*67e74705SXin Li if (!Ctor && !ClassDecl->isLiteral())
5247*67e74705SXin Li return false;
5248*67e74705SXin Li
5249*67e74705SXin Li // -- every constructor involved in initializing [...] base class
5250*67e74705SXin Li // sub-objects shall be a constexpr constructor;
5251*67e74705SXin Li // -- the assignment operator selected to copy/move each direct base
5252*67e74705SXin Li // class is a constexpr function, and
5253*67e74705SXin Li for (const auto &B : ClassDecl->bases()) {
5254*67e74705SXin Li const RecordType *BaseType = B.getType()->getAs<RecordType>();
5255*67e74705SXin Li if (!BaseType) continue;
5256*67e74705SXin Li
5257*67e74705SXin Li CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5258*67e74705SXin Li if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
5259*67e74705SXin Li InheritedCtor, Inherited))
5260*67e74705SXin Li return false;
5261*67e74705SXin Li }
5262*67e74705SXin Li
5263*67e74705SXin Li // -- every constructor involved in initializing non-static data members
5264*67e74705SXin Li // [...] shall be a constexpr constructor;
5265*67e74705SXin Li // -- every non-static data member and base class sub-object shall be
5266*67e74705SXin Li // initialized
5267*67e74705SXin Li // -- for each non-static data member of X that is of class type (or array
5268*67e74705SXin Li // thereof), the assignment operator selected to copy/move that member is
5269*67e74705SXin Li // a constexpr function
5270*67e74705SXin Li for (const auto *F : ClassDecl->fields()) {
5271*67e74705SXin Li if (F->isInvalidDecl())
5272*67e74705SXin Li continue;
5273*67e74705SXin Li if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
5274*67e74705SXin Li continue;
5275*67e74705SXin Li QualType BaseType = S.Context.getBaseElementType(F->getType());
5276*67e74705SXin Li if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5277*67e74705SXin Li CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5278*67e74705SXin Li if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5279*67e74705SXin Li BaseType.getCVRQualifiers(),
5280*67e74705SXin Li ConstArg && !F->isMutable()))
5281*67e74705SXin Li return false;
5282*67e74705SXin Li } else if (CSM == Sema::CXXDefaultConstructor) {
5283*67e74705SXin Li return false;
5284*67e74705SXin Li }
5285*67e74705SXin Li }
5286*67e74705SXin Li
5287*67e74705SXin Li // All OK, it's constexpr!
5288*67e74705SXin Li return true;
5289*67e74705SXin Li }
5290*67e74705SXin Li
5291*67e74705SXin Li static Sema::ImplicitExceptionSpecification
computeImplicitExceptionSpec(Sema & S,SourceLocation Loc,CXXMethodDecl * MD)5292*67e74705SXin Li computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5293*67e74705SXin Li switch (S.getSpecialMember(MD)) {
5294*67e74705SXin Li case Sema::CXXDefaultConstructor:
5295*67e74705SXin Li return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5296*67e74705SXin Li case Sema::CXXCopyConstructor:
5297*67e74705SXin Li return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5298*67e74705SXin Li case Sema::CXXCopyAssignment:
5299*67e74705SXin Li return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5300*67e74705SXin Li case Sema::CXXMoveConstructor:
5301*67e74705SXin Li return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5302*67e74705SXin Li case Sema::CXXMoveAssignment:
5303*67e74705SXin Li return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5304*67e74705SXin Li case Sema::CXXDestructor:
5305*67e74705SXin Li return S.ComputeDefaultedDtorExceptionSpec(MD);
5306*67e74705SXin Li case Sema::CXXInvalid:
5307*67e74705SXin Li break;
5308*67e74705SXin Li }
5309*67e74705SXin Li assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5310*67e74705SXin Li "only special members have implicit exception specs");
5311*67e74705SXin Li return S.ComputeInheritingCtorExceptionSpec(Loc,
5312*67e74705SXin Li cast<CXXConstructorDecl>(MD));
5313*67e74705SXin Li }
5314*67e74705SXin Li
getImplicitMethodEPI(Sema & S,CXXMethodDecl * MD)5315*67e74705SXin Li static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5316*67e74705SXin Li CXXMethodDecl *MD) {
5317*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI;
5318*67e74705SXin Li
5319*67e74705SXin Li // Build an exception specification pointing back at this member.
5320*67e74705SXin Li EPI.ExceptionSpec.Type = EST_Unevaluated;
5321*67e74705SXin Li EPI.ExceptionSpec.SourceDecl = MD;
5322*67e74705SXin Li
5323*67e74705SXin Li // Set the calling convention to the default for C++ instance methods.
5324*67e74705SXin Li EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5325*67e74705SXin Li S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5326*67e74705SXin Li /*IsCXXMethod=*/true));
5327*67e74705SXin Li return EPI;
5328*67e74705SXin Li }
5329*67e74705SXin Li
EvaluateImplicitExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)5330*67e74705SXin Li void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5331*67e74705SXin Li const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5332*67e74705SXin Li if (FPT->getExceptionSpecType() != EST_Unevaluated)
5333*67e74705SXin Li return;
5334*67e74705SXin Li
5335*67e74705SXin Li // Evaluate the exception specification.
5336*67e74705SXin Li auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5337*67e74705SXin Li
5338*67e74705SXin Li // Update the type of the special member to use it.
5339*67e74705SXin Li UpdateExceptionSpec(MD, ESI);
5340*67e74705SXin Li
5341*67e74705SXin Li // A user-provided destructor can be defined outside the class. When that
5342*67e74705SXin Li // happens, be sure to update the exception specification on both
5343*67e74705SXin Li // declarations.
5344*67e74705SXin Li const FunctionProtoType *CanonicalFPT =
5345*67e74705SXin Li MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5346*67e74705SXin Li if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5347*67e74705SXin Li UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5348*67e74705SXin Li }
5349*67e74705SXin Li
CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl * MD)5350*67e74705SXin Li void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5351*67e74705SXin Li CXXRecordDecl *RD = MD->getParent();
5352*67e74705SXin Li CXXSpecialMember CSM = getSpecialMember(MD);
5353*67e74705SXin Li
5354*67e74705SXin Li assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5355*67e74705SXin Li "not an explicitly-defaulted special member");
5356*67e74705SXin Li
5357*67e74705SXin Li // Whether this was the first-declared instance of the constructor.
5358*67e74705SXin Li // This affects whether we implicitly add an exception spec and constexpr.
5359*67e74705SXin Li bool First = MD == MD->getCanonicalDecl();
5360*67e74705SXin Li
5361*67e74705SXin Li bool HadError = false;
5362*67e74705SXin Li
5363*67e74705SXin Li // C++11 [dcl.fct.def.default]p1:
5364*67e74705SXin Li // A function that is explicitly defaulted shall
5365*67e74705SXin Li // -- be a special member function (checked elsewhere),
5366*67e74705SXin Li // -- have the same type (except for ref-qualifiers, and except that a
5367*67e74705SXin Li // copy operation can take a non-const reference) as an implicit
5368*67e74705SXin Li // declaration, and
5369*67e74705SXin Li // -- not have default arguments.
5370*67e74705SXin Li unsigned ExpectedParams = 1;
5371*67e74705SXin Li if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5372*67e74705SXin Li ExpectedParams = 0;
5373*67e74705SXin Li if (MD->getNumParams() != ExpectedParams) {
5374*67e74705SXin Li // This also checks for default arguments: a copy or move constructor with a
5375*67e74705SXin Li // default argument is classified as a default constructor, and assignment
5376*67e74705SXin Li // operations and destructors can't have default arguments.
5377*67e74705SXin Li Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5378*67e74705SXin Li << CSM << MD->getSourceRange();
5379*67e74705SXin Li HadError = true;
5380*67e74705SXin Li } else if (MD->isVariadic()) {
5381*67e74705SXin Li Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5382*67e74705SXin Li << CSM << MD->getSourceRange();
5383*67e74705SXin Li HadError = true;
5384*67e74705SXin Li }
5385*67e74705SXin Li
5386*67e74705SXin Li const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5387*67e74705SXin Li
5388*67e74705SXin Li bool CanHaveConstParam = false;
5389*67e74705SXin Li if (CSM == CXXCopyConstructor)
5390*67e74705SXin Li CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5391*67e74705SXin Li else if (CSM == CXXCopyAssignment)
5392*67e74705SXin Li CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5393*67e74705SXin Li
5394*67e74705SXin Li QualType ReturnType = Context.VoidTy;
5395*67e74705SXin Li if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5396*67e74705SXin Li // Check for return type matching.
5397*67e74705SXin Li ReturnType = Type->getReturnType();
5398*67e74705SXin Li QualType ExpectedReturnType =
5399*67e74705SXin Li Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5400*67e74705SXin Li if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5401*67e74705SXin Li Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5402*67e74705SXin Li << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5403*67e74705SXin Li HadError = true;
5404*67e74705SXin Li }
5405*67e74705SXin Li
5406*67e74705SXin Li // A defaulted special member cannot have cv-qualifiers.
5407*67e74705SXin Li if (Type->getTypeQuals()) {
5408*67e74705SXin Li Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5409*67e74705SXin Li << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5410*67e74705SXin Li HadError = true;
5411*67e74705SXin Li }
5412*67e74705SXin Li }
5413*67e74705SXin Li
5414*67e74705SXin Li // Check for parameter type matching.
5415*67e74705SXin Li QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5416*67e74705SXin Li bool HasConstParam = false;
5417*67e74705SXin Li if (ExpectedParams && ArgType->isReferenceType()) {
5418*67e74705SXin Li // Argument must be reference to possibly-const T.
5419*67e74705SXin Li QualType ReferentType = ArgType->getPointeeType();
5420*67e74705SXin Li HasConstParam = ReferentType.isConstQualified();
5421*67e74705SXin Li
5422*67e74705SXin Li if (ReferentType.isVolatileQualified()) {
5423*67e74705SXin Li Diag(MD->getLocation(),
5424*67e74705SXin Li diag::err_defaulted_special_member_volatile_param) << CSM;
5425*67e74705SXin Li HadError = true;
5426*67e74705SXin Li }
5427*67e74705SXin Li
5428*67e74705SXin Li if (HasConstParam && !CanHaveConstParam) {
5429*67e74705SXin Li if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5430*67e74705SXin Li Diag(MD->getLocation(),
5431*67e74705SXin Li diag::err_defaulted_special_member_copy_const_param)
5432*67e74705SXin Li << (CSM == CXXCopyAssignment);
5433*67e74705SXin Li // FIXME: Explain why this special member can't be const.
5434*67e74705SXin Li } else {
5435*67e74705SXin Li Diag(MD->getLocation(),
5436*67e74705SXin Li diag::err_defaulted_special_member_move_const_param)
5437*67e74705SXin Li << (CSM == CXXMoveAssignment);
5438*67e74705SXin Li }
5439*67e74705SXin Li HadError = true;
5440*67e74705SXin Li }
5441*67e74705SXin Li } else if (ExpectedParams) {
5442*67e74705SXin Li // A copy assignment operator can take its argument by value, but a
5443*67e74705SXin Li // defaulted one cannot.
5444*67e74705SXin Li assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5445*67e74705SXin Li Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5446*67e74705SXin Li HadError = true;
5447*67e74705SXin Li }
5448*67e74705SXin Li
5449*67e74705SXin Li // C++11 [dcl.fct.def.default]p2:
5450*67e74705SXin Li // An explicitly-defaulted function may be declared constexpr only if it
5451*67e74705SXin Li // would have been implicitly declared as constexpr,
5452*67e74705SXin Li // Do not apply this rule to members of class templates, since core issue 1358
5453*67e74705SXin Li // makes such functions always instantiate to constexpr functions. For
5454*67e74705SXin Li // functions which cannot be constexpr (for non-constructors in C++11 and for
5455*67e74705SXin Li // destructors in C++1y), this is checked elsewhere.
5456*67e74705SXin Li bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5457*67e74705SXin Li HasConstParam);
5458*67e74705SXin Li if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5459*67e74705SXin Li : isa<CXXConstructorDecl>(MD)) &&
5460*67e74705SXin Li MD->isConstexpr() && !Constexpr &&
5461*67e74705SXin Li MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5462*67e74705SXin Li Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5463*67e74705SXin Li // FIXME: Explain why the special member can't be constexpr.
5464*67e74705SXin Li HadError = true;
5465*67e74705SXin Li }
5466*67e74705SXin Li
5467*67e74705SXin Li // and may have an explicit exception-specification only if it is compatible
5468*67e74705SXin Li // with the exception-specification on the implicit declaration.
5469*67e74705SXin Li if (Type->hasExceptionSpec()) {
5470*67e74705SXin Li // Delay the check if this is the first declaration of the special member,
5471*67e74705SXin Li // since we may not have parsed some necessary in-class initializers yet.
5472*67e74705SXin Li if (First) {
5473*67e74705SXin Li // If the exception specification needs to be instantiated, do so now,
5474*67e74705SXin Li // before we clobber it with an EST_Unevaluated specification below.
5475*67e74705SXin Li if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5476*67e74705SXin Li InstantiateExceptionSpec(MD->getLocStart(), MD);
5477*67e74705SXin Li Type = MD->getType()->getAs<FunctionProtoType>();
5478*67e74705SXin Li }
5479*67e74705SXin Li DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5480*67e74705SXin Li } else
5481*67e74705SXin Li CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5482*67e74705SXin Li }
5483*67e74705SXin Li
5484*67e74705SXin Li // If a function is explicitly defaulted on its first declaration,
5485*67e74705SXin Li if (First) {
5486*67e74705SXin Li // -- it is implicitly considered to be constexpr if the implicit
5487*67e74705SXin Li // definition would be,
5488*67e74705SXin Li MD->setConstexpr(Constexpr);
5489*67e74705SXin Li
5490*67e74705SXin Li // -- it is implicitly considered to have the same exception-specification
5491*67e74705SXin Li // as if it had been implicitly declared,
5492*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5493*67e74705SXin Li EPI.ExceptionSpec.Type = EST_Unevaluated;
5494*67e74705SXin Li EPI.ExceptionSpec.SourceDecl = MD;
5495*67e74705SXin Li MD->setType(Context.getFunctionType(ReturnType,
5496*67e74705SXin Li llvm::makeArrayRef(&ArgType,
5497*67e74705SXin Li ExpectedParams),
5498*67e74705SXin Li EPI));
5499*67e74705SXin Li }
5500*67e74705SXin Li
5501*67e74705SXin Li if (ShouldDeleteSpecialMember(MD, CSM)) {
5502*67e74705SXin Li if (First) {
5503*67e74705SXin Li SetDeclDeleted(MD, MD->getLocation());
5504*67e74705SXin Li } else {
5505*67e74705SXin Li // C++11 [dcl.fct.def.default]p4:
5506*67e74705SXin Li // [For a] user-provided explicitly-defaulted function [...] if such a
5507*67e74705SXin Li // function is implicitly defined as deleted, the program is ill-formed.
5508*67e74705SXin Li Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5509*67e74705SXin Li ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
5510*67e74705SXin Li HadError = true;
5511*67e74705SXin Li }
5512*67e74705SXin Li }
5513*67e74705SXin Li
5514*67e74705SXin Li if (HadError)
5515*67e74705SXin Li MD->setInvalidDecl();
5516*67e74705SXin Li }
5517*67e74705SXin Li
5518*67e74705SXin Li /// Check whether the exception specification provided for an
5519*67e74705SXin Li /// explicitly-defaulted special member matches the exception specification
5520*67e74705SXin Li /// that would have been generated for an implicit special member, per
5521*67e74705SXin Li /// C++11 [dcl.fct.def.default]p2.
CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl * MD,const FunctionProtoType * SpecifiedType)5522*67e74705SXin Li void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5523*67e74705SXin Li CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5524*67e74705SXin Li // If the exception specification was explicitly specified but hadn't been
5525*67e74705SXin Li // parsed when the method was defaulted, grab it now.
5526*67e74705SXin Li if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5527*67e74705SXin Li SpecifiedType =
5528*67e74705SXin Li MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5529*67e74705SXin Li
5530*67e74705SXin Li // Compute the implicit exception specification.
5531*67e74705SXin Li CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5532*67e74705SXin Li /*IsCXXMethod=*/true);
5533*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI(CC);
5534*67e74705SXin Li EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5535*67e74705SXin Li .getExceptionSpec();
5536*67e74705SXin Li const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5537*67e74705SXin Li Context.getFunctionType(Context.VoidTy, None, EPI));
5538*67e74705SXin Li
5539*67e74705SXin Li // Ensure that it matches.
5540*67e74705SXin Li CheckEquivalentExceptionSpec(
5541*67e74705SXin Li PDiag(diag::err_incorrect_defaulted_exception_spec)
5542*67e74705SXin Li << getSpecialMember(MD), PDiag(),
5543*67e74705SXin Li ImplicitType, SourceLocation(),
5544*67e74705SXin Li SpecifiedType, MD->getLocation());
5545*67e74705SXin Li }
5546*67e74705SXin Li
CheckDelayedMemberExceptionSpecs()5547*67e74705SXin Li void Sema::CheckDelayedMemberExceptionSpecs() {
5548*67e74705SXin Li decltype(DelayedExceptionSpecChecks) Checks;
5549*67e74705SXin Li decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5550*67e74705SXin Li
5551*67e74705SXin Li std::swap(Checks, DelayedExceptionSpecChecks);
5552*67e74705SXin Li std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5553*67e74705SXin Li
5554*67e74705SXin Li // Perform any deferred checking of exception specifications for virtual
5555*67e74705SXin Li // destructors.
5556*67e74705SXin Li for (auto &Check : Checks)
5557*67e74705SXin Li CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5558*67e74705SXin Li
5559*67e74705SXin Li // Check that any explicitly-defaulted methods have exception specifications
5560*67e74705SXin Li // compatible with their implicit exception specifications.
5561*67e74705SXin Li for (auto &Spec : Specs)
5562*67e74705SXin Li CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5563*67e74705SXin Li }
5564*67e74705SXin Li
5565*67e74705SXin Li namespace {
5566*67e74705SXin Li struct SpecialMemberDeletionInfo {
5567*67e74705SXin Li Sema &S;
5568*67e74705SXin Li CXXMethodDecl *MD;
5569*67e74705SXin Li Sema::CXXSpecialMember CSM;
5570*67e74705SXin Li Sema::InheritedConstructorInfo *ICI;
5571*67e74705SXin Li bool Diagnose;
5572*67e74705SXin Li
5573*67e74705SXin Li // Properties of the special member, computed for convenience.
5574*67e74705SXin Li bool IsConstructor, IsAssignment, IsMove, ConstArg;
5575*67e74705SXin Li SourceLocation Loc;
5576*67e74705SXin Li
5577*67e74705SXin Li bool AllFieldsAreConst;
5578*67e74705SXin Li
SpecialMemberDeletionInfo__anon75252e180711::SpecialMemberDeletionInfo5579*67e74705SXin Li SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5580*67e74705SXin Li Sema::CXXSpecialMember CSM,
5581*67e74705SXin Li Sema::InheritedConstructorInfo *ICI, bool Diagnose)
5582*67e74705SXin Li : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
5583*67e74705SXin Li IsConstructor(false), IsAssignment(false), IsMove(false),
5584*67e74705SXin Li ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
5585*67e74705SXin Li switch (CSM) {
5586*67e74705SXin Li case Sema::CXXDefaultConstructor:
5587*67e74705SXin Li case Sema::CXXCopyConstructor:
5588*67e74705SXin Li IsConstructor = true;
5589*67e74705SXin Li break;
5590*67e74705SXin Li case Sema::CXXMoveConstructor:
5591*67e74705SXin Li IsConstructor = true;
5592*67e74705SXin Li IsMove = true;
5593*67e74705SXin Li break;
5594*67e74705SXin Li case Sema::CXXCopyAssignment:
5595*67e74705SXin Li IsAssignment = true;
5596*67e74705SXin Li break;
5597*67e74705SXin Li case Sema::CXXMoveAssignment:
5598*67e74705SXin Li IsAssignment = true;
5599*67e74705SXin Li IsMove = true;
5600*67e74705SXin Li break;
5601*67e74705SXin Li case Sema::CXXDestructor:
5602*67e74705SXin Li break;
5603*67e74705SXin Li case Sema::CXXInvalid:
5604*67e74705SXin Li llvm_unreachable("invalid special member kind");
5605*67e74705SXin Li }
5606*67e74705SXin Li
5607*67e74705SXin Li if (MD->getNumParams()) {
5608*67e74705SXin Li if (const ReferenceType *RT =
5609*67e74705SXin Li MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5610*67e74705SXin Li ConstArg = RT->getPointeeType().isConstQualified();
5611*67e74705SXin Li }
5612*67e74705SXin Li }
5613*67e74705SXin Li
inUnion__anon75252e180711::SpecialMemberDeletionInfo5614*67e74705SXin Li bool inUnion() const { return MD->getParent()->isUnion(); }
5615*67e74705SXin Li
getEffectiveCSM__anon75252e180711::SpecialMemberDeletionInfo5616*67e74705SXin Li Sema::CXXSpecialMember getEffectiveCSM() {
5617*67e74705SXin Li return ICI ? Sema::CXXInvalid : CSM;
5618*67e74705SXin Li }
5619*67e74705SXin Li
5620*67e74705SXin Li /// Look up the corresponding special member in the given class.
lookupIn__anon75252e180711::SpecialMemberDeletionInfo5621*67e74705SXin Li Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5622*67e74705SXin Li unsigned Quals, bool IsMutable) {
5623*67e74705SXin Li return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5624*67e74705SXin Li ConstArg && !IsMutable);
5625*67e74705SXin Li }
5626*67e74705SXin Li
5627*67e74705SXin Li typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5628*67e74705SXin Li
5629*67e74705SXin Li bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5630*67e74705SXin Li bool shouldDeleteForField(FieldDecl *FD);
5631*67e74705SXin Li bool shouldDeleteForAllConstMembers();
5632*67e74705SXin Li
5633*67e74705SXin Li bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5634*67e74705SXin Li unsigned Quals);
5635*67e74705SXin Li bool shouldDeleteForSubobjectCall(Subobject Subobj,
5636*67e74705SXin Li Sema::SpecialMemberOverloadResult *SMOR,
5637*67e74705SXin Li bool IsDtorCallInCtor);
5638*67e74705SXin Li
5639*67e74705SXin Li bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5640*67e74705SXin Li };
5641*67e74705SXin Li }
5642*67e74705SXin Li
5643*67e74705SXin Li /// Is the given special member inaccessible when used on the given
5644*67e74705SXin Li /// sub-object.
isAccessible(Subobject Subobj,CXXMethodDecl * target)5645*67e74705SXin Li bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5646*67e74705SXin Li CXXMethodDecl *target) {
5647*67e74705SXin Li /// If we're operating on a base class, the object type is the
5648*67e74705SXin Li /// type of this special member.
5649*67e74705SXin Li QualType objectTy;
5650*67e74705SXin Li AccessSpecifier access = target->getAccess();
5651*67e74705SXin Li if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5652*67e74705SXin Li objectTy = S.Context.getTypeDeclType(MD->getParent());
5653*67e74705SXin Li access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5654*67e74705SXin Li
5655*67e74705SXin Li // If we're operating on a field, the object type is the type of the field.
5656*67e74705SXin Li } else {
5657*67e74705SXin Li objectTy = S.Context.getTypeDeclType(target->getParent());
5658*67e74705SXin Li }
5659*67e74705SXin Li
5660*67e74705SXin Li return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5661*67e74705SXin Li }
5662*67e74705SXin Li
5663*67e74705SXin Li /// Check whether we should delete a special member due to the implicit
5664*67e74705SXin Li /// definition containing a call to a special member of a subobject.
shouldDeleteForSubobjectCall(Subobject Subobj,Sema::SpecialMemberOverloadResult * SMOR,bool IsDtorCallInCtor)5665*67e74705SXin Li bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5666*67e74705SXin Li Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5667*67e74705SXin Li bool IsDtorCallInCtor) {
5668*67e74705SXin Li CXXMethodDecl *Decl = SMOR->getMethod();
5669*67e74705SXin Li FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5670*67e74705SXin Li
5671*67e74705SXin Li int DiagKind = -1;
5672*67e74705SXin Li
5673*67e74705SXin Li if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5674*67e74705SXin Li DiagKind = !Decl ? 0 : 1;
5675*67e74705SXin Li else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5676*67e74705SXin Li DiagKind = 2;
5677*67e74705SXin Li else if (!isAccessible(Subobj, Decl))
5678*67e74705SXin Li DiagKind = 3;
5679*67e74705SXin Li else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5680*67e74705SXin Li !Decl->isTrivial()) {
5681*67e74705SXin Li // A member of a union must have a trivial corresponding special member.
5682*67e74705SXin Li // As a weird special case, a destructor call from a union's constructor
5683*67e74705SXin Li // must be accessible and non-deleted, but need not be trivial. Such a
5684*67e74705SXin Li // destructor is never actually called, but is semantically checked as
5685*67e74705SXin Li // if it were.
5686*67e74705SXin Li DiagKind = 4;
5687*67e74705SXin Li }
5688*67e74705SXin Li
5689*67e74705SXin Li if (DiagKind == -1)
5690*67e74705SXin Li return false;
5691*67e74705SXin Li
5692*67e74705SXin Li if (Diagnose) {
5693*67e74705SXin Li if (Field) {
5694*67e74705SXin Li S.Diag(Field->getLocation(),
5695*67e74705SXin Li diag::note_deleted_special_member_class_subobject)
5696*67e74705SXin Li << getEffectiveCSM() << MD->getParent() << /*IsField*/true
5697*67e74705SXin Li << Field << DiagKind << IsDtorCallInCtor;
5698*67e74705SXin Li } else {
5699*67e74705SXin Li CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5700*67e74705SXin Li S.Diag(Base->getLocStart(),
5701*67e74705SXin Li diag::note_deleted_special_member_class_subobject)
5702*67e74705SXin Li << getEffectiveCSM() << MD->getParent() << /*IsField*/false
5703*67e74705SXin Li << Base->getType() << DiagKind << IsDtorCallInCtor;
5704*67e74705SXin Li }
5705*67e74705SXin Li
5706*67e74705SXin Li if (DiagKind == 1)
5707*67e74705SXin Li S.NoteDeletedFunction(Decl);
5708*67e74705SXin Li // FIXME: Explain inaccessibility if DiagKind == 3.
5709*67e74705SXin Li }
5710*67e74705SXin Li
5711*67e74705SXin Li return true;
5712*67e74705SXin Li }
5713*67e74705SXin Li
5714*67e74705SXin Li /// Check whether we should delete a special member function due to having a
5715*67e74705SXin Li /// direct or virtual base class or non-static data member of class type M.
shouldDeleteForClassSubobject(CXXRecordDecl * Class,Subobject Subobj,unsigned Quals)5716*67e74705SXin Li bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5717*67e74705SXin Li CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5718*67e74705SXin Li FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5719*67e74705SXin Li bool IsMutable = Field && Field->isMutable();
5720*67e74705SXin Li
5721*67e74705SXin Li // C++11 [class.ctor]p5:
5722*67e74705SXin Li // -- any direct or virtual base class, or non-static data member with no
5723*67e74705SXin Li // brace-or-equal-initializer, has class type M (or array thereof) and
5724*67e74705SXin Li // either M has no default constructor or overload resolution as applied
5725*67e74705SXin Li // to M's default constructor results in an ambiguity or in a function
5726*67e74705SXin Li // that is deleted or inaccessible
5727*67e74705SXin Li // C++11 [class.copy]p11, C++11 [class.copy]p23:
5728*67e74705SXin Li // -- a direct or virtual base class B that cannot be copied/moved because
5729*67e74705SXin Li // overload resolution, as applied to B's corresponding special member,
5730*67e74705SXin Li // results in an ambiguity or a function that is deleted or inaccessible
5731*67e74705SXin Li // from the defaulted special member
5732*67e74705SXin Li // C++11 [class.dtor]p5:
5733*67e74705SXin Li // -- any direct or virtual base class [...] has a type with a destructor
5734*67e74705SXin Li // that is deleted or inaccessible
5735*67e74705SXin Li if (!(CSM == Sema::CXXDefaultConstructor &&
5736*67e74705SXin Li Field && Field->hasInClassInitializer()) &&
5737*67e74705SXin Li shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5738*67e74705SXin Li false))
5739*67e74705SXin Li return true;
5740*67e74705SXin Li
5741*67e74705SXin Li // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5742*67e74705SXin Li // -- any direct or virtual base class or non-static data member has a
5743*67e74705SXin Li // type with a destructor that is deleted or inaccessible
5744*67e74705SXin Li if (IsConstructor) {
5745*67e74705SXin Li Sema::SpecialMemberOverloadResult *SMOR =
5746*67e74705SXin Li S.LookupSpecialMember(Class, Sema::CXXDestructor,
5747*67e74705SXin Li false, false, false, false, false);
5748*67e74705SXin Li if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5749*67e74705SXin Li return true;
5750*67e74705SXin Li }
5751*67e74705SXin Li
5752*67e74705SXin Li return false;
5753*67e74705SXin Li }
5754*67e74705SXin Li
5755*67e74705SXin Li /// Check whether we should delete a special member function due to the class
5756*67e74705SXin Li /// having a particular direct or virtual base class.
shouldDeleteForBase(CXXBaseSpecifier * Base)5757*67e74705SXin Li bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5758*67e74705SXin Li CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5759*67e74705SXin Li // If program is correct, BaseClass cannot be null, but if it is, the error
5760*67e74705SXin Li // must be reported elsewhere.
5761*67e74705SXin Li if (!BaseClass)
5762*67e74705SXin Li return false;
5763*67e74705SXin Li // If we have an inheriting constructor, check whether we're calling an
5764*67e74705SXin Li // inherited constructor instead of a default constructor.
5765*67e74705SXin Li if (ICI) {
5766*67e74705SXin Li assert(CSM == Sema::CXXDefaultConstructor);
5767*67e74705SXin Li auto *BaseCtor =
5768*67e74705SXin Li ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
5769*67e74705SXin Li ->getInheritedConstructor()
5770*67e74705SXin Li .getConstructor())
5771*67e74705SXin Li .first;
5772*67e74705SXin Li if (BaseCtor) {
5773*67e74705SXin Li if (BaseCtor->isDeleted() && Diagnose) {
5774*67e74705SXin Li S.Diag(Base->getLocStart(),
5775*67e74705SXin Li diag::note_deleted_special_member_class_subobject)
5776*67e74705SXin Li << getEffectiveCSM() << MD->getParent() << /*IsField*/false
5777*67e74705SXin Li << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
5778*67e74705SXin Li S.NoteDeletedFunction(BaseCtor);
5779*67e74705SXin Li }
5780*67e74705SXin Li return BaseCtor->isDeleted();
5781*67e74705SXin Li }
5782*67e74705SXin Li }
5783*67e74705SXin Li return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5784*67e74705SXin Li }
5785*67e74705SXin Li
5786*67e74705SXin Li /// Check whether we should delete a special member function due to the class
5787*67e74705SXin Li /// having a particular non-static data member.
shouldDeleteForField(FieldDecl * FD)5788*67e74705SXin Li bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5789*67e74705SXin Li QualType FieldType = S.Context.getBaseElementType(FD->getType());
5790*67e74705SXin Li CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5791*67e74705SXin Li
5792*67e74705SXin Li if (CSM == Sema::CXXDefaultConstructor) {
5793*67e74705SXin Li // For a default constructor, all references must be initialized in-class
5794*67e74705SXin Li // and, if a union, it must have a non-const member.
5795*67e74705SXin Li if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5796*67e74705SXin Li if (Diagnose)
5797*67e74705SXin Li S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5798*67e74705SXin Li << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
5799*67e74705SXin Li return true;
5800*67e74705SXin Li }
5801*67e74705SXin Li // C++11 [class.ctor]p5: any non-variant non-static data member of
5802*67e74705SXin Li // const-qualified type (or array thereof) with no
5803*67e74705SXin Li // brace-or-equal-initializer does not have a user-provided default
5804*67e74705SXin Li // constructor.
5805*67e74705SXin Li if (!inUnion() && FieldType.isConstQualified() &&
5806*67e74705SXin Li !FD->hasInClassInitializer() &&
5807*67e74705SXin Li (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5808*67e74705SXin Li if (Diagnose)
5809*67e74705SXin Li S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5810*67e74705SXin Li << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
5811*67e74705SXin Li return true;
5812*67e74705SXin Li }
5813*67e74705SXin Li
5814*67e74705SXin Li if (inUnion() && !FieldType.isConstQualified())
5815*67e74705SXin Li AllFieldsAreConst = false;
5816*67e74705SXin Li } else if (CSM == Sema::CXXCopyConstructor) {
5817*67e74705SXin Li // For a copy constructor, data members must not be of rvalue reference
5818*67e74705SXin Li // type.
5819*67e74705SXin Li if (FieldType->isRValueReferenceType()) {
5820*67e74705SXin Li if (Diagnose)
5821*67e74705SXin Li S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5822*67e74705SXin Li << MD->getParent() << FD << FieldType;
5823*67e74705SXin Li return true;
5824*67e74705SXin Li }
5825*67e74705SXin Li } else if (IsAssignment) {
5826*67e74705SXin Li // For an assignment operator, data members must not be of reference type.
5827*67e74705SXin Li if (FieldType->isReferenceType()) {
5828*67e74705SXin Li if (Diagnose)
5829*67e74705SXin Li S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5830*67e74705SXin Li << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5831*67e74705SXin Li return true;
5832*67e74705SXin Li }
5833*67e74705SXin Li if (!FieldRecord && FieldType.isConstQualified()) {
5834*67e74705SXin Li // C++11 [class.copy]p23:
5835*67e74705SXin Li // -- a non-static data member of const non-class type (or array thereof)
5836*67e74705SXin Li if (Diagnose)
5837*67e74705SXin Li S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5838*67e74705SXin Li << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5839*67e74705SXin Li return true;
5840*67e74705SXin Li }
5841*67e74705SXin Li }
5842*67e74705SXin Li
5843*67e74705SXin Li if (FieldRecord) {
5844*67e74705SXin Li // Some additional restrictions exist on the variant members.
5845*67e74705SXin Li if (!inUnion() && FieldRecord->isUnion() &&
5846*67e74705SXin Li FieldRecord->isAnonymousStructOrUnion()) {
5847*67e74705SXin Li bool AllVariantFieldsAreConst = true;
5848*67e74705SXin Li
5849*67e74705SXin Li // FIXME: Handle anonymous unions declared within anonymous unions.
5850*67e74705SXin Li for (auto *UI : FieldRecord->fields()) {
5851*67e74705SXin Li QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5852*67e74705SXin Li
5853*67e74705SXin Li if (!UnionFieldType.isConstQualified())
5854*67e74705SXin Li AllVariantFieldsAreConst = false;
5855*67e74705SXin Li
5856*67e74705SXin Li CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5857*67e74705SXin Li if (UnionFieldRecord &&
5858*67e74705SXin Li shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5859*67e74705SXin Li UnionFieldType.getCVRQualifiers()))
5860*67e74705SXin Li return true;
5861*67e74705SXin Li }
5862*67e74705SXin Li
5863*67e74705SXin Li // At least one member in each anonymous union must be non-const
5864*67e74705SXin Li if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5865*67e74705SXin Li !FieldRecord->field_empty()) {
5866*67e74705SXin Li if (Diagnose)
5867*67e74705SXin Li S.Diag(FieldRecord->getLocation(),
5868*67e74705SXin Li diag::note_deleted_default_ctor_all_const)
5869*67e74705SXin Li << !!ICI << MD->getParent() << /*anonymous union*/1;
5870*67e74705SXin Li return true;
5871*67e74705SXin Li }
5872*67e74705SXin Li
5873*67e74705SXin Li // Don't check the implicit member of the anonymous union type.
5874*67e74705SXin Li // This is technically non-conformant, but sanity demands it.
5875*67e74705SXin Li return false;
5876*67e74705SXin Li }
5877*67e74705SXin Li
5878*67e74705SXin Li if (shouldDeleteForClassSubobject(FieldRecord, FD,
5879*67e74705SXin Li FieldType.getCVRQualifiers()))
5880*67e74705SXin Li return true;
5881*67e74705SXin Li }
5882*67e74705SXin Li
5883*67e74705SXin Li return false;
5884*67e74705SXin Li }
5885*67e74705SXin Li
5886*67e74705SXin Li /// C++11 [class.ctor] p5:
5887*67e74705SXin Li /// A defaulted default constructor for a class X is defined as deleted if
5888*67e74705SXin Li /// X is a union and all of its variant members are of const-qualified type.
shouldDeleteForAllConstMembers()5889*67e74705SXin Li bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5890*67e74705SXin Li // This is a silly definition, because it gives an empty union a deleted
5891*67e74705SXin Li // default constructor. Don't do that.
5892*67e74705SXin Li if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5893*67e74705SXin Li !MD->getParent()->field_empty()) {
5894*67e74705SXin Li if (Diagnose)
5895*67e74705SXin Li S.Diag(MD->getParent()->getLocation(),
5896*67e74705SXin Li diag::note_deleted_default_ctor_all_const)
5897*67e74705SXin Li << !!ICI << MD->getParent() << /*not anonymous union*/0;
5898*67e74705SXin Li return true;
5899*67e74705SXin Li }
5900*67e74705SXin Li return false;
5901*67e74705SXin Li }
5902*67e74705SXin Li
5903*67e74705SXin Li /// Determine whether a defaulted special member function should be defined as
5904*67e74705SXin Li /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5905*67e74705SXin Li /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
ShouldDeleteSpecialMember(CXXMethodDecl * MD,CXXSpecialMember CSM,InheritedConstructorInfo * ICI,bool Diagnose)5906*67e74705SXin Li bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5907*67e74705SXin Li InheritedConstructorInfo *ICI,
5908*67e74705SXin Li bool Diagnose) {
5909*67e74705SXin Li if (MD->isInvalidDecl())
5910*67e74705SXin Li return false;
5911*67e74705SXin Li CXXRecordDecl *RD = MD->getParent();
5912*67e74705SXin Li assert(!RD->isDependentType() && "do deletion after instantiation");
5913*67e74705SXin Li if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5914*67e74705SXin Li return false;
5915*67e74705SXin Li
5916*67e74705SXin Li // C++11 [expr.lambda.prim]p19:
5917*67e74705SXin Li // The closure type associated with a lambda-expression has a
5918*67e74705SXin Li // deleted (8.4.3) default constructor and a deleted copy
5919*67e74705SXin Li // assignment operator.
5920*67e74705SXin Li if (RD->isLambda() &&
5921*67e74705SXin Li (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5922*67e74705SXin Li if (Diagnose)
5923*67e74705SXin Li Diag(RD->getLocation(), diag::note_lambda_decl);
5924*67e74705SXin Li return true;
5925*67e74705SXin Li }
5926*67e74705SXin Li
5927*67e74705SXin Li // For an anonymous struct or union, the copy and assignment special members
5928*67e74705SXin Li // will never be used, so skip the check. For an anonymous union declared at
5929*67e74705SXin Li // namespace scope, the constructor and destructor are used.
5930*67e74705SXin Li if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5931*67e74705SXin Li RD->isAnonymousStructOrUnion())
5932*67e74705SXin Li return false;
5933*67e74705SXin Li
5934*67e74705SXin Li // C++11 [class.copy]p7, p18:
5935*67e74705SXin Li // If the class definition declares a move constructor or move assignment
5936*67e74705SXin Li // operator, an implicitly declared copy constructor or copy assignment
5937*67e74705SXin Li // operator is defined as deleted.
5938*67e74705SXin Li if (MD->isImplicit() &&
5939*67e74705SXin Li (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5940*67e74705SXin Li CXXMethodDecl *UserDeclaredMove = nullptr;
5941*67e74705SXin Li
5942*67e74705SXin Li // In Microsoft mode, a user-declared move only causes the deletion of the
5943*67e74705SXin Li // corresponding copy operation, not both copy operations.
5944*67e74705SXin Li if (RD->hasUserDeclaredMoveConstructor() &&
5945*67e74705SXin Li (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5946*67e74705SXin Li if (!Diagnose) return true;
5947*67e74705SXin Li
5948*67e74705SXin Li // Find any user-declared move constructor.
5949*67e74705SXin Li for (auto *I : RD->ctors()) {
5950*67e74705SXin Li if (I->isMoveConstructor()) {
5951*67e74705SXin Li UserDeclaredMove = I;
5952*67e74705SXin Li break;
5953*67e74705SXin Li }
5954*67e74705SXin Li }
5955*67e74705SXin Li assert(UserDeclaredMove);
5956*67e74705SXin Li } else if (RD->hasUserDeclaredMoveAssignment() &&
5957*67e74705SXin Li (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5958*67e74705SXin Li if (!Diagnose) return true;
5959*67e74705SXin Li
5960*67e74705SXin Li // Find any user-declared move assignment operator.
5961*67e74705SXin Li for (auto *I : RD->methods()) {
5962*67e74705SXin Li if (I->isMoveAssignmentOperator()) {
5963*67e74705SXin Li UserDeclaredMove = I;
5964*67e74705SXin Li break;
5965*67e74705SXin Li }
5966*67e74705SXin Li }
5967*67e74705SXin Li assert(UserDeclaredMove);
5968*67e74705SXin Li }
5969*67e74705SXin Li
5970*67e74705SXin Li if (UserDeclaredMove) {
5971*67e74705SXin Li Diag(UserDeclaredMove->getLocation(),
5972*67e74705SXin Li diag::note_deleted_copy_user_declared_move)
5973*67e74705SXin Li << (CSM == CXXCopyAssignment) << RD
5974*67e74705SXin Li << UserDeclaredMove->isMoveAssignmentOperator();
5975*67e74705SXin Li return true;
5976*67e74705SXin Li }
5977*67e74705SXin Li }
5978*67e74705SXin Li
5979*67e74705SXin Li // Do access control from the special member function
5980*67e74705SXin Li ContextRAII MethodContext(*this, MD);
5981*67e74705SXin Li
5982*67e74705SXin Li // C++11 [class.dtor]p5:
5983*67e74705SXin Li // -- for a virtual destructor, lookup of the non-array deallocation function
5984*67e74705SXin Li // results in an ambiguity or in a function that is deleted or inaccessible
5985*67e74705SXin Li if (CSM == CXXDestructor && MD->isVirtual()) {
5986*67e74705SXin Li FunctionDecl *OperatorDelete = nullptr;
5987*67e74705SXin Li DeclarationName Name =
5988*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5989*67e74705SXin Li if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5990*67e74705SXin Li OperatorDelete, false)) {
5991*67e74705SXin Li if (Diagnose)
5992*67e74705SXin Li Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5993*67e74705SXin Li return true;
5994*67e74705SXin Li }
5995*67e74705SXin Li }
5996*67e74705SXin Li
5997*67e74705SXin Li SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
5998*67e74705SXin Li
5999*67e74705SXin Li for (auto &BI : RD->bases())
6000*67e74705SXin Li if (!BI.isVirtual() &&
6001*67e74705SXin Li SMI.shouldDeleteForBase(&BI))
6002*67e74705SXin Li return true;
6003*67e74705SXin Li
6004*67e74705SXin Li // Per DR1611, do not consider virtual bases of constructors of abstract
6005*67e74705SXin Li // classes, since we are not going to construct them.
6006*67e74705SXin Li if (!RD->isAbstract() || !SMI.IsConstructor) {
6007*67e74705SXin Li for (auto &BI : RD->vbases())
6008*67e74705SXin Li if (SMI.shouldDeleteForBase(&BI))
6009*67e74705SXin Li return true;
6010*67e74705SXin Li }
6011*67e74705SXin Li
6012*67e74705SXin Li for (auto *FI : RD->fields())
6013*67e74705SXin Li if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6014*67e74705SXin Li SMI.shouldDeleteForField(FI))
6015*67e74705SXin Li return true;
6016*67e74705SXin Li
6017*67e74705SXin Li if (SMI.shouldDeleteForAllConstMembers())
6018*67e74705SXin Li return true;
6019*67e74705SXin Li
6020*67e74705SXin Li if (getLangOpts().CUDA) {
6021*67e74705SXin Li // We should delete the special member in CUDA mode if target inference
6022*67e74705SXin Li // failed.
6023*67e74705SXin Li return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6024*67e74705SXin Li Diagnose);
6025*67e74705SXin Li }
6026*67e74705SXin Li
6027*67e74705SXin Li return false;
6028*67e74705SXin Li }
6029*67e74705SXin Li
6030*67e74705SXin Li /// Perform lookup for a special member of the specified kind, and determine
6031*67e74705SXin Li /// whether it is trivial. If the triviality can be determined without the
6032*67e74705SXin Li /// lookup, skip it. This is intended for use when determining whether a
6033*67e74705SXin Li /// special member of a containing object is trivial, and thus does not ever
6034*67e74705SXin Li /// perform overload resolution for default constructors.
6035*67e74705SXin Li ///
6036*67e74705SXin Li /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6037*67e74705SXin Li /// member that was most likely to be intended to be trivial, if any.
findTrivialSpecialMember(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,unsigned Quals,bool ConstRHS,CXXMethodDecl ** Selected)6038*67e74705SXin Li static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6039*67e74705SXin Li Sema::CXXSpecialMember CSM, unsigned Quals,
6040*67e74705SXin Li bool ConstRHS, CXXMethodDecl **Selected) {
6041*67e74705SXin Li if (Selected)
6042*67e74705SXin Li *Selected = nullptr;
6043*67e74705SXin Li
6044*67e74705SXin Li switch (CSM) {
6045*67e74705SXin Li case Sema::CXXInvalid:
6046*67e74705SXin Li llvm_unreachable("not a special member");
6047*67e74705SXin Li
6048*67e74705SXin Li case Sema::CXXDefaultConstructor:
6049*67e74705SXin Li // C++11 [class.ctor]p5:
6050*67e74705SXin Li // A default constructor is trivial if:
6051*67e74705SXin Li // - all the [direct subobjects] have trivial default constructors
6052*67e74705SXin Li //
6053*67e74705SXin Li // Note, no overload resolution is performed in this case.
6054*67e74705SXin Li if (RD->hasTrivialDefaultConstructor())
6055*67e74705SXin Li return true;
6056*67e74705SXin Li
6057*67e74705SXin Li if (Selected) {
6058*67e74705SXin Li // If there's a default constructor which could have been trivial, dig it
6059*67e74705SXin Li // out. Otherwise, if there's any user-provided default constructor, point
6060*67e74705SXin Li // to that as an example of why there's not a trivial one.
6061*67e74705SXin Li CXXConstructorDecl *DefCtor = nullptr;
6062*67e74705SXin Li if (RD->needsImplicitDefaultConstructor())
6063*67e74705SXin Li S.DeclareImplicitDefaultConstructor(RD);
6064*67e74705SXin Li for (auto *CI : RD->ctors()) {
6065*67e74705SXin Li if (!CI->isDefaultConstructor())
6066*67e74705SXin Li continue;
6067*67e74705SXin Li DefCtor = CI;
6068*67e74705SXin Li if (!DefCtor->isUserProvided())
6069*67e74705SXin Li break;
6070*67e74705SXin Li }
6071*67e74705SXin Li
6072*67e74705SXin Li *Selected = DefCtor;
6073*67e74705SXin Li }
6074*67e74705SXin Li
6075*67e74705SXin Li return false;
6076*67e74705SXin Li
6077*67e74705SXin Li case Sema::CXXDestructor:
6078*67e74705SXin Li // C++11 [class.dtor]p5:
6079*67e74705SXin Li // A destructor is trivial if:
6080*67e74705SXin Li // - all the direct [subobjects] have trivial destructors
6081*67e74705SXin Li if (RD->hasTrivialDestructor())
6082*67e74705SXin Li return true;
6083*67e74705SXin Li
6084*67e74705SXin Li if (Selected) {
6085*67e74705SXin Li if (RD->needsImplicitDestructor())
6086*67e74705SXin Li S.DeclareImplicitDestructor(RD);
6087*67e74705SXin Li *Selected = RD->getDestructor();
6088*67e74705SXin Li }
6089*67e74705SXin Li
6090*67e74705SXin Li return false;
6091*67e74705SXin Li
6092*67e74705SXin Li case Sema::CXXCopyConstructor:
6093*67e74705SXin Li // C++11 [class.copy]p12:
6094*67e74705SXin Li // A copy constructor is trivial if:
6095*67e74705SXin Li // - the constructor selected to copy each direct [subobject] is trivial
6096*67e74705SXin Li if (RD->hasTrivialCopyConstructor()) {
6097*67e74705SXin Li if (Quals == Qualifiers::Const)
6098*67e74705SXin Li // We must either select the trivial copy constructor or reach an
6099*67e74705SXin Li // ambiguity; no need to actually perform overload resolution.
6100*67e74705SXin Li return true;
6101*67e74705SXin Li } else if (!Selected) {
6102*67e74705SXin Li return false;
6103*67e74705SXin Li }
6104*67e74705SXin Li // In C++98, we are not supposed to perform overload resolution here, but we
6105*67e74705SXin Li // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6106*67e74705SXin Li // cases like B as having a non-trivial copy constructor:
6107*67e74705SXin Li // struct A { template<typename T> A(T&); };
6108*67e74705SXin Li // struct B { mutable A a; };
6109*67e74705SXin Li goto NeedOverloadResolution;
6110*67e74705SXin Li
6111*67e74705SXin Li case Sema::CXXCopyAssignment:
6112*67e74705SXin Li // C++11 [class.copy]p25:
6113*67e74705SXin Li // A copy assignment operator is trivial if:
6114*67e74705SXin Li // - the assignment operator selected to copy each direct [subobject] is
6115*67e74705SXin Li // trivial
6116*67e74705SXin Li if (RD->hasTrivialCopyAssignment()) {
6117*67e74705SXin Li if (Quals == Qualifiers::Const)
6118*67e74705SXin Li return true;
6119*67e74705SXin Li } else if (!Selected) {
6120*67e74705SXin Li return false;
6121*67e74705SXin Li }
6122*67e74705SXin Li // In C++98, we are not supposed to perform overload resolution here, but we
6123*67e74705SXin Li // treat that as a language defect.
6124*67e74705SXin Li goto NeedOverloadResolution;
6125*67e74705SXin Li
6126*67e74705SXin Li case Sema::CXXMoveConstructor:
6127*67e74705SXin Li case Sema::CXXMoveAssignment:
6128*67e74705SXin Li NeedOverloadResolution:
6129*67e74705SXin Li Sema::SpecialMemberOverloadResult *SMOR =
6130*67e74705SXin Li lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6131*67e74705SXin Li
6132*67e74705SXin Li // The standard doesn't describe how to behave if the lookup is ambiguous.
6133*67e74705SXin Li // We treat it as not making the member non-trivial, just like the standard
6134*67e74705SXin Li // mandates for the default constructor. This should rarely matter, because
6135*67e74705SXin Li // the member will also be deleted.
6136*67e74705SXin Li if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6137*67e74705SXin Li return true;
6138*67e74705SXin Li
6139*67e74705SXin Li if (!SMOR->getMethod()) {
6140*67e74705SXin Li assert(SMOR->getKind() ==
6141*67e74705SXin Li Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6142*67e74705SXin Li return false;
6143*67e74705SXin Li }
6144*67e74705SXin Li
6145*67e74705SXin Li // We deliberately don't check if we found a deleted special member. We're
6146*67e74705SXin Li // not supposed to!
6147*67e74705SXin Li if (Selected)
6148*67e74705SXin Li *Selected = SMOR->getMethod();
6149*67e74705SXin Li return SMOR->getMethod()->isTrivial();
6150*67e74705SXin Li }
6151*67e74705SXin Li
6152*67e74705SXin Li llvm_unreachable("unknown special method kind");
6153*67e74705SXin Li }
6154*67e74705SXin Li
findUserDeclaredCtor(CXXRecordDecl * RD)6155*67e74705SXin Li static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6156*67e74705SXin Li for (auto *CI : RD->ctors())
6157*67e74705SXin Li if (!CI->isImplicit())
6158*67e74705SXin Li return CI;
6159*67e74705SXin Li
6160*67e74705SXin Li // Look for constructor templates.
6161*67e74705SXin Li typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6162*67e74705SXin Li for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6163*67e74705SXin Li if (CXXConstructorDecl *CD =
6164*67e74705SXin Li dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6165*67e74705SXin Li return CD;
6166*67e74705SXin Li }
6167*67e74705SXin Li
6168*67e74705SXin Li return nullptr;
6169*67e74705SXin Li }
6170*67e74705SXin Li
6171*67e74705SXin Li /// The kind of subobject we are checking for triviality. The values of this
6172*67e74705SXin Li /// enumeration are used in diagnostics.
6173*67e74705SXin Li enum TrivialSubobjectKind {
6174*67e74705SXin Li /// The subobject is a base class.
6175*67e74705SXin Li TSK_BaseClass,
6176*67e74705SXin Li /// The subobject is a non-static data member.
6177*67e74705SXin Li TSK_Field,
6178*67e74705SXin Li /// The object is actually the complete object.
6179*67e74705SXin Li TSK_CompleteObject
6180*67e74705SXin Li };
6181*67e74705SXin Li
6182*67e74705SXin Li /// Check whether the special member selected for a given type would be trivial.
checkTrivialSubobjectCall(Sema & S,SourceLocation SubobjLoc,QualType SubType,bool ConstRHS,Sema::CXXSpecialMember CSM,TrivialSubobjectKind Kind,bool Diagnose)6183*67e74705SXin Li static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6184*67e74705SXin Li QualType SubType, bool ConstRHS,
6185*67e74705SXin Li Sema::CXXSpecialMember CSM,
6186*67e74705SXin Li TrivialSubobjectKind Kind,
6187*67e74705SXin Li bool Diagnose) {
6188*67e74705SXin Li CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6189*67e74705SXin Li if (!SubRD)
6190*67e74705SXin Li return true;
6191*67e74705SXin Li
6192*67e74705SXin Li CXXMethodDecl *Selected;
6193*67e74705SXin Li if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6194*67e74705SXin Li ConstRHS, Diagnose ? &Selected : nullptr))
6195*67e74705SXin Li return true;
6196*67e74705SXin Li
6197*67e74705SXin Li if (Diagnose) {
6198*67e74705SXin Li if (ConstRHS)
6199*67e74705SXin Li SubType.addConst();
6200*67e74705SXin Li
6201*67e74705SXin Li if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6202*67e74705SXin Li S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6203*67e74705SXin Li << Kind << SubType.getUnqualifiedType();
6204*67e74705SXin Li if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6205*67e74705SXin Li S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6206*67e74705SXin Li } else if (!Selected)
6207*67e74705SXin Li S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6208*67e74705SXin Li << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6209*67e74705SXin Li else if (Selected->isUserProvided()) {
6210*67e74705SXin Li if (Kind == TSK_CompleteObject)
6211*67e74705SXin Li S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6212*67e74705SXin Li << Kind << SubType.getUnqualifiedType() << CSM;
6213*67e74705SXin Li else {
6214*67e74705SXin Li S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6215*67e74705SXin Li << Kind << SubType.getUnqualifiedType() << CSM;
6216*67e74705SXin Li S.Diag(Selected->getLocation(), diag::note_declared_at);
6217*67e74705SXin Li }
6218*67e74705SXin Li } else {
6219*67e74705SXin Li if (Kind != TSK_CompleteObject)
6220*67e74705SXin Li S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6221*67e74705SXin Li << Kind << SubType.getUnqualifiedType() << CSM;
6222*67e74705SXin Li
6223*67e74705SXin Li // Explain why the defaulted or deleted special member isn't trivial.
6224*67e74705SXin Li S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6225*67e74705SXin Li }
6226*67e74705SXin Li }
6227*67e74705SXin Li
6228*67e74705SXin Li return false;
6229*67e74705SXin Li }
6230*67e74705SXin Li
6231*67e74705SXin Li /// Check whether the members of a class type allow a special member to be
6232*67e74705SXin Li /// trivial.
checkTrivialClassMembers(Sema & S,CXXRecordDecl * RD,Sema::CXXSpecialMember CSM,bool ConstArg,bool Diagnose)6233*67e74705SXin Li static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6234*67e74705SXin Li Sema::CXXSpecialMember CSM,
6235*67e74705SXin Li bool ConstArg, bool Diagnose) {
6236*67e74705SXin Li for (const auto *FI : RD->fields()) {
6237*67e74705SXin Li if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6238*67e74705SXin Li continue;
6239*67e74705SXin Li
6240*67e74705SXin Li QualType FieldType = S.Context.getBaseElementType(FI->getType());
6241*67e74705SXin Li
6242*67e74705SXin Li // Pretend anonymous struct or union members are members of this class.
6243*67e74705SXin Li if (FI->isAnonymousStructOrUnion()) {
6244*67e74705SXin Li if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6245*67e74705SXin Li CSM, ConstArg, Diagnose))
6246*67e74705SXin Li return false;
6247*67e74705SXin Li continue;
6248*67e74705SXin Li }
6249*67e74705SXin Li
6250*67e74705SXin Li // C++11 [class.ctor]p5:
6251*67e74705SXin Li // A default constructor is trivial if [...]
6252*67e74705SXin Li // -- no non-static data member of its class has a
6253*67e74705SXin Li // brace-or-equal-initializer
6254*67e74705SXin Li if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6255*67e74705SXin Li if (Diagnose)
6256*67e74705SXin Li S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6257*67e74705SXin Li return false;
6258*67e74705SXin Li }
6259*67e74705SXin Li
6260*67e74705SXin Li // Objective C ARC 4.3.5:
6261*67e74705SXin Li // [...] nontrivally ownership-qualified types are [...] not trivially
6262*67e74705SXin Li // default constructible, copy constructible, move constructible, copy
6263*67e74705SXin Li // assignable, move assignable, or destructible [...]
6264*67e74705SXin Li if (S.getLangOpts().ObjCAutoRefCount &&
6265*67e74705SXin Li FieldType.hasNonTrivialObjCLifetime()) {
6266*67e74705SXin Li if (Diagnose)
6267*67e74705SXin Li S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6268*67e74705SXin Li << RD << FieldType.getObjCLifetime();
6269*67e74705SXin Li return false;
6270*67e74705SXin Li }
6271*67e74705SXin Li
6272*67e74705SXin Li bool ConstRHS = ConstArg && !FI->isMutable();
6273*67e74705SXin Li if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6274*67e74705SXin Li CSM, TSK_Field, Diagnose))
6275*67e74705SXin Li return false;
6276*67e74705SXin Li }
6277*67e74705SXin Li
6278*67e74705SXin Li return true;
6279*67e74705SXin Li }
6280*67e74705SXin Li
6281*67e74705SXin Li /// Diagnose why the specified class does not have a trivial special member of
6282*67e74705SXin Li /// the given kind.
DiagnoseNontrivial(const CXXRecordDecl * RD,CXXSpecialMember CSM)6283*67e74705SXin Li void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6284*67e74705SXin Li QualType Ty = Context.getRecordType(RD);
6285*67e74705SXin Li
6286*67e74705SXin Li bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6287*67e74705SXin Li checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6288*67e74705SXin Li TSK_CompleteObject, /*Diagnose*/true);
6289*67e74705SXin Li }
6290*67e74705SXin Li
6291*67e74705SXin Li /// Determine whether a defaulted or deleted special member function is trivial,
6292*67e74705SXin Li /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6293*67e74705SXin Li /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
SpecialMemberIsTrivial(CXXMethodDecl * MD,CXXSpecialMember CSM,bool Diagnose)6294*67e74705SXin Li bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6295*67e74705SXin Li bool Diagnose) {
6296*67e74705SXin Li assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6297*67e74705SXin Li
6298*67e74705SXin Li CXXRecordDecl *RD = MD->getParent();
6299*67e74705SXin Li
6300*67e74705SXin Li bool ConstArg = false;
6301*67e74705SXin Li
6302*67e74705SXin Li // C++11 [class.copy]p12, p25: [DR1593]
6303*67e74705SXin Li // A [special member] is trivial if [...] its parameter-type-list is
6304*67e74705SXin Li // equivalent to the parameter-type-list of an implicit declaration [...]
6305*67e74705SXin Li switch (CSM) {
6306*67e74705SXin Li case CXXDefaultConstructor:
6307*67e74705SXin Li case CXXDestructor:
6308*67e74705SXin Li // Trivial default constructors and destructors cannot have parameters.
6309*67e74705SXin Li break;
6310*67e74705SXin Li
6311*67e74705SXin Li case CXXCopyConstructor:
6312*67e74705SXin Li case CXXCopyAssignment: {
6313*67e74705SXin Li // Trivial copy operations always have const, non-volatile parameter types.
6314*67e74705SXin Li ConstArg = true;
6315*67e74705SXin Li const ParmVarDecl *Param0 = MD->getParamDecl(0);
6316*67e74705SXin Li const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6317*67e74705SXin Li if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6318*67e74705SXin Li if (Diagnose)
6319*67e74705SXin Li Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6320*67e74705SXin Li << Param0->getSourceRange() << Param0->getType()
6321*67e74705SXin Li << Context.getLValueReferenceType(
6322*67e74705SXin Li Context.getRecordType(RD).withConst());
6323*67e74705SXin Li return false;
6324*67e74705SXin Li }
6325*67e74705SXin Li break;
6326*67e74705SXin Li }
6327*67e74705SXin Li
6328*67e74705SXin Li case CXXMoveConstructor:
6329*67e74705SXin Li case CXXMoveAssignment: {
6330*67e74705SXin Li // Trivial move operations always have non-cv-qualified parameters.
6331*67e74705SXin Li const ParmVarDecl *Param0 = MD->getParamDecl(0);
6332*67e74705SXin Li const RValueReferenceType *RT =
6333*67e74705SXin Li Param0->getType()->getAs<RValueReferenceType>();
6334*67e74705SXin Li if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6335*67e74705SXin Li if (Diagnose)
6336*67e74705SXin Li Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6337*67e74705SXin Li << Param0->getSourceRange() << Param0->getType()
6338*67e74705SXin Li << Context.getRValueReferenceType(Context.getRecordType(RD));
6339*67e74705SXin Li return false;
6340*67e74705SXin Li }
6341*67e74705SXin Li break;
6342*67e74705SXin Li }
6343*67e74705SXin Li
6344*67e74705SXin Li case CXXInvalid:
6345*67e74705SXin Li llvm_unreachable("not a special member");
6346*67e74705SXin Li }
6347*67e74705SXin Li
6348*67e74705SXin Li if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6349*67e74705SXin Li if (Diagnose)
6350*67e74705SXin Li Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6351*67e74705SXin Li diag::note_nontrivial_default_arg)
6352*67e74705SXin Li << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6353*67e74705SXin Li return false;
6354*67e74705SXin Li }
6355*67e74705SXin Li if (MD->isVariadic()) {
6356*67e74705SXin Li if (Diagnose)
6357*67e74705SXin Li Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6358*67e74705SXin Li return false;
6359*67e74705SXin Li }
6360*67e74705SXin Li
6361*67e74705SXin Li // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6362*67e74705SXin Li // A copy/move [constructor or assignment operator] is trivial if
6363*67e74705SXin Li // -- the [member] selected to copy/move each direct base class subobject
6364*67e74705SXin Li // is trivial
6365*67e74705SXin Li //
6366*67e74705SXin Li // C++11 [class.copy]p12, C++11 [class.copy]p25:
6367*67e74705SXin Li // A [default constructor or destructor] is trivial if
6368*67e74705SXin Li // -- all the direct base classes have trivial [default constructors or
6369*67e74705SXin Li // destructors]
6370*67e74705SXin Li for (const auto &BI : RD->bases())
6371*67e74705SXin Li if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6372*67e74705SXin Li ConstArg, CSM, TSK_BaseClass, Diagnose))
6373*67e74705SXin Li return false;
6374*67e74705SXin Li
6375*67e74705SXin Li // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6376*67e74705SXin Li // A copy/move [constructor or assignment operator] for a class X is
6377*67e74705SXin Li // trivial if
6378*67e74705SXin Li // -- for each non-static data member of X that is of class type (or array
6379*67e74705SXin Li // thereof), the constructor selected to copy/move that member is
6380*67e74705SXin Li // trivial
6381*67e74705SXin Li //
6382*67e74705SXin Li // C++11 [class.copy]p12, C++11 [class.copy]p25:
6383*67e74705SXin Li // A [default constructor or destructor] is trivial if
6384*67e74705SXin Li // -- for all of the non-static data members of its class that are of class
6385*67e74705SXin Li // type (or array thereof), each such class has a trivial [default
6386*67e74705SXin Li // constructor or destructor]
6387*67e74705SXin Li if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6388*67e74705SXin Li return false;
6389*67e74705SXin Li
6390*67e74705SXin Li // C++11 [class.dtor]p5:
6391*67e74705SXin Li // A destructor is trivial if [...]
6392*67e74705SXin Li // -- the destructor is not virtual
6393*67e74705SXin Li if (CSM == CXXDestructor && MD->isVirtual()) {
6394*67e74705SXin Li if (Diagnose)
6395*67e74705SXin Li Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6396*67e74705SXin Li return false;
6397*67e74705SXin Li }
6398*67e74705SXin Li
6399*67e74705SXin Li // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6400*67e74705SXin Li // A [special member] for class X is trivial if [...]
6401*67e74705SXin Li // -- class X has no virtual functions and no virtual base classes
6402*67e74705SXin Li if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6403*67e74705SXin Li if (!Diagnose)
6404*67e74705SXin Li return false;
6405*67e74705SXin Li
6406*67e74705SXin Li if (RD->getNumVBases()) {
6407*67e74705SXin Li // Check for virtual bases. We already know that the corresponding
6408*67e74705SXin Li // member in all bases is trivial, so vbases must all be direct.
6409*67e74705SXin Li CXXBaseSpecifier &BS = *RD->vbases_begin();
6410*67e74705SXin Li assert(BS.isVirtual());
6411*67e74705SXin Li Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6412*67e74705SXin Li return false;
6413*67e74705SXin Li }
6414*67e74705SXin Li
6415*67e74705SXin Li // Must have a virtual method.
6416*67e74705SXin Li for (const auto *MI : RD->methods()) {
6417*67e74705SXin Li if (MI->isVirtual()) {
6418*67e74705SXin Li SourceLocation MLoc = MI->getLocStart();
6419*67e74705SXin Li Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6420*67e74705SXin Li return false;
6421*67e74705SXin Li }
6422*67e74705SXin Li }
6423*67e74705SXin Li
6424*67e74705SXin Li llvm_unreachable("dynamic class with no vbases and no virtual functions");
6425*67e74705SXin Li }
6426*67e74705SXin Li
6427*67e74705SXin Li // Looks like it's trivial!
6428*67e74705SXin Li return true;
6429*67e74705SXin Li }
6430*67e74705SXin Li
6431*67e74705SXin Li namespace {
6432*67e74705SXin Li struct FindHiddenVirtualMethod {
6433*67e74705SXin Li Sema *S;
6434*67e74705SXin Li CXXMethodDecl *Method;
6435*67e74705SXin Li llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6436*67e74705SXin Li SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6437*67e74705SXin Li
6438*67e74705SXin Li private:
6439*67e74705SXin Li /// Check whether any most overriden method from MD in Methods
CheckMostOverridenMethods__anon75252e180811::FindHiddenVirtualMethod6440*67e74705SXin Li static bool CheckMostOverridenMethods(
6441*67e74705SXin Li const CXXMethodDecl *MD,
6442*67e74705SXin Li const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6443*67e74705SXin Li if (MD->size_overridden_methods() == 0)
6444*67e74705SXin Li return Methods.count(MD->getCanonicalDecl());
6445*67e74705SXin Li for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6446*67e74705SXin Li E = MD->end_overridden_methods();
6447*67e74705SXin Li I != E; ++I)
6448*67e74705SXin Li if (CheckMostOverridenMethods(*I, Methods))
6449*67e74705SXin Li return true;
6450*67e74705SXin Li return false;
6451*67e74705SXin Li }
6452*67e74705SXin Li
6453*67e74705SXin Li public:
6454*67e74705SXin Li /// Member lookup function that determines whether a given C++
6455*67e74705SXin Li /// method overloads virtual methods in a base class without overriding any,
6456*67e74705SXin Li /// to be used with CXXRecordDecl::lookupInBases().
operator ()__anon75252e180811::FindHiddenVirtualMethod6457*67e74705SXin Li bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6458*67e74705SXin Li RecordDecl *BaseRecord =
6459*67e74705SXin Li Specifier->getType()->getAs<RecordType>()->getDecl();
6460*67e74705SXin Li
6461*67e74705SXin Li DeclarationName Name = Method->getDeclName();
6462*67e74705SXin Li assert(Name.getNameKind() == DeclarationName::Identifier);
6463*67e74705SXin Li
6464*67e74705SXin Li bool foundSameNameMethod = false;
6465*67e74705SXin Li SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6466*67e74705SXin Li for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6467*67e74705SXin Li Path.Decls = Path.Decls.slice(1)) {
6468*67e74705SXin Li NamedDecl *D = Path.Decls.front();
6469*67e74705SXin Li if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6470*67e74705SXin Li MD = MD->getCanonicalDecl();
6471*67e74705SXin Li foundSameNameMethod = true;
6472*67e74705SXin Li // Interested only in hidden virtual methods.
6473*67e74705SXin Li if (!MD->isVirtual())
6474*67e74705SXin Li continue;
6475*67e74705SXin Li // If the method we are checking overrides a method from its base
6476*67e74705SXin Li // don't warn about the other overloaded methods. Clang deviates from
6477*67e74705SXin Li // GCC by only diagnosing overloads of inherited virtual functions that
6478*67e74705SXin Li // do not override any other virtual functions in the base. GCC's
6479*67e74705SXin Li // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6480*67e74705SXin Li // function from a base class. These cases may be better served by a
6481*67e74705SXin Li // warning (not specific to virtual functions) on call sites when the
6482*67e74705SXin Li // call would select a different function from the base class, were it
6483*67e74705SXin Li // visible.
6484*67e74705SXin Li // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6485*67e74705SXin Li if (!S->IsOverload(Method, MD, false))
6486*67e74705SXin Li return true;
6487*67e74705SXin Li // Collect the overload only if its hidden.
6488*67e74705SXin Li if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6489*67e74705SXin Li overloadedMethods.push_back(MD);
6490*67e74705SXin Li }
6491*67e74705SXin Li }
6492*67e74705SXin Li
6493*67e74705SXin Li if (foundSameNameMethod)
6494*67e74705SXin Li OverloadedMethods.append(overloadedMethods.begin(),
6495*67e74705SXin Li overloadedMethods.end());
6496*67e74705SXin Li return foundSameNameMethod;
6497*67e74705SXin Li }
6498*67e74705SXin Li };
6499*67e74705SXin Li } // end anonymous namespace
6500*67e74705SXin Li
6501*67e74705SXin Li /// \brief Add the most overriden methods from MD to Methods
AddMostOverridenMethods(const CXXMethodDecl * MD,llvm::SmallPtrSetImpl<const CXXMethodDecl * > & Methods)6502*67e74705SXin Li static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6503*67e74705SXin Li llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6504*67e74705SXin Li if (MD->size_overridden_methods() == 0)
6505*67e74705SXin Li Methods.insert(MD->getCanonicalDecl());
6506*67e74705SXin Li for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6507*67e74705SXin Li E = MD->end_overridden_methods();
6508*67e74705SXin Li I != E; ++I)
6509*67e74705SXin Li AddMostOverridenMethods(*I, Methods);
6510*67e74705SXin Li }
6511*67e74705SXin Li
6512*67e74705SXin Li /// \brief Check if a method overloads virtual methods in a base class without
6513*67e74705SXin Li /// overriding any.
FindHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)6514*67e74705SXin Li void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6515*67e74705SXin Li SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6516*67e74705SXin Li if (!MD->getDeclName().isIdentifier())
6517*67e74705SXin Li return;
6518*67e74705SXin Li
6519*67e74705SXin Li CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6520*67e74705SXin Li /*bool RecordPaths=*/false,
6521*67e74705SXin Li /*bool DetectVirtual=*/false);
6522*67e74705SXin Li FindHiddenVirtualMethod FHVM;
6523*67e74705SXin Li FHVM.Method = MD;
6524*67e74705SXin Li FHVM.S = this;
6525*67e74705SXin Li
6526*67e74705SXin Li // Keep the base methods that were overriden or introduced in the subclass
6527*67e74705SXin Li // by 'using' in a set. A base method not in this set is hidden.
6528*67e74705SXin Li CXXRecordDecl *DC = MD->getParent();
6529*67e74705SXin Li DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6530*67e74705SXin Li for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6531*67e74705SXin Li NamedDecl *ND = *I;
6532*67e74705SXin Li if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6533*67e74705SXin Li ND = shad->getTargetDecl();
6534*67e74705SXin Li if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6535*67e74705SXin Li AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
6536*67e74705SXin Li }
6537*67e74705SXin Li
6538*67e74705SXin Li if (DC->lookupInBases(FHVM, Paths))
6539*67e74705SXin Li OverloadedMethods = FHVM.OverloadedMethods;
6540*67e74705SXin Li }
6541*67e74705SXin Li
NoteHiddenVirtualMethods(CXXMethodDecl * MD,SmallVectorImpl<CXXMethodDecl * > & OverloadedMethods)6542*67e74705SXin Li void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6543*67e74705SXin Li SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6544*67e74705SXin Li for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6545*67e74705SXin Li CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6546*67e74705SXin Li PartialDiagnostic PD = PDiag(
6547*67e74705SXin Li diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6548*67e74705SXin Li HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6549*67e74705SXin Li Diag(overloadedMD->getLocation(), PD);
6550*67e74705SXin Li }
6551*67e74705SXin Li }
6552*67e74705SXin Li
6553*67e74705SXin Li /// \brief Diagnose methods which overload virtual methods in a base class
6554*67e74705SXin Li /// without overriding any.
DiagnoseHiddenVirtualMethods(CXXMethodDecl * MD)6555*67e74705SXin Li void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6556*67e74705SXin Li if (MD->isInvalidDecl())
6557*67e74705SXin Li return;
6558*67e74705SXin Li
6559*67e74705SXin Li if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6560*67e74705SXin Li return;
6561*67e74705SXin Li
6562*67e74705SXin Li SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6563*67e74705SXin Li FindHiddenVirtualMethods(MD, OverloadedMethods);
6564*67e74705SXin Li if (!OverloadedMethods.empty()) {
6565*67e74705SXin Li Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6566*67e74705SXin Li << MD << (OverloadedMethods.size() > 1);
6567*67e74705SXin Li
6568*67e74705SXin Li NoteHiddenVirtualMethods(MD, OverloadedMethods);
6569*67e74705SXin Li }
6570*67e74705SXin Li }
6571*67e74705SXin Li
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,AttributeList * AttrList)6572*67e74705SXin Li void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6573*67e74705SXin Li Decl *TagDecl,
6574*67e74705SXin Li SourceLocation LBrac,
6575*67e74705SXin Li SourceLocation RBrac,
6576*67e74705SXin Li AttributeList *AttrList) {
6577*67e74705SXin Li if (!TagDecl)
6578*67e74705SXin Li return;
6579*67e74705SXin Li
6580*67e74705SXin Li AdjustDeclIfTemplate(TagDecl);
6581*67e74705SXin Li
6582*67e74705SXin Li for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6583*67e74705SXin Li if (l->getKind() != AttributeList::AT_Visibility)
6584*67e74705SXin Li continue;
6585*67e74705SXin Li l->setInvalid();
6586*67e74705SXin Li Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6587*67e74705SXin Li l->getName();
6588*67e74705SXin Li }
6589*67e74705SXin Li
6590*67e74705SXin Li ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6591*67e74705SXin Li // strict aliasing violation!
6592*67e74705SXin Li reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6593*67e74705SXin Li FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6594*67e74705SXin Li
6595*67e74705SXin Li CheckCompletedCXXClass(
6596*67e74705SXin Li dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6597*67e74705SXin Li }
6598*67e74705SXin Li
6599*67e74705SXin Li /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6600*67e74705SXin Li /// special functions, such as the default constructor, copy
6601*67e74705SXin Li /// constructor, or destructor, to the given C++ class (C++
6602*67e74705SXin Li /// [special]p1). This routine can only be executed just before the
6603*67e74705SXin Li /// definition of the class is complete.
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)6604*67e74705SXin Li void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6605*67e74705SXin Li if (ClassDecl->needsImplicitDefaultConstructor()) {
6606*67e74705SXin Li ++ASTContext::NumImplicitDefaultConstructors;
6607*67e74705SXin Li
6608*67e74705SXin Li if (ClassDecl->hasInheritedConstructor())
6609*67e74705SXin Li DeclareImplicitDefaultConstructor(ClassDecl);
6610*67e74705SXin Li }
6611*67e74705SXin Li
6612*67e74705SXin Li if (ClassDecl->needsImplicitCopyConstructor()) {
6613*67e74705SXin Li ++ASTContext::NumImplicitCopyConstructors;
6614*67e74705SXin Li
6615*67e74705SXin Li // If the properties or semantics of the copy constructor couldn't be
6616*67e74705SXin Li // determined while the class was being declared, force a declaration
6617*67e74705SXin Li // of it now.
6618*67e74705SXin Li if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
6619*67e74705SXin Li ClassDecl->hasInheritedConstructor())
6620*67e74705SXin Li DeclareImplicitCopyConstructor(ClassDecl);
6621*67e74705SXin Li }
6622*67e74705SXin Li
6623*67e74705SXin Li if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6624*67e74705SXin Li ++ASTContext::NumImplicitMoveConstructors;
6625*67e74705SXin Li
6626*67e74705SXin Li if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
6627*67e74705SXin Li ClassDecl->hasInheritedConstructor())
6628*67e74705SXin Li DeclareImplicitMoveConstructor(ClassDecl);
6629*67e74705SXin Li }
6630*67e74705SXin Li
6631*67e74705SXin Li if (ClassDecl->needsImplicitCopyAssignment()) {
6632*67e74705SXin Li ++ASTContext::NumImplicitCopyAssignmentOperators;
6633*67e74705SXin Li
6634*67e74705SXin Li // If we have a dynamic class, then the copy assignment operator may be
6635*67e74705SXin Li // virtual, so we have to declare it immediately. This ensures that, e.g.,
6636*67e74705SXin Li // it shows up in the right place in the vtable and that we diagnose
6637*67e74705SXin Li // problems with the implicit exception specification.
6638*67e74705SXin Li if (ClassDecl->isDynamicClass() ||
6639*67e74705SXin Li ClassDecl->needsOverloadResolutionForCopyAssignment() ||
6640*67e74705SXin Li ClassDecl->hasInheritedAssignment())
6641*67e74705SXin Li DeclareImplicitCopyAssignment(ClassDecl);
6642*67e74705SXin Li }
6643*67e74705SXin Li
6644*67e74705SXin Li if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6645*67e74705SXin Li ++ASTContext::NumImplicitMoveAssignmentOperators;
6646*67e74705SXin Li
6647*67e74705SXin Li // Likewise for the move assignment operator.
6648*67e74705SXin Li if (ClassDecl->isDynamicClass() ||
6649*67e74705SXin Li ClassDecl->needsOverloadResolutionForMoveAssignment() ||
6650*67e74705SXin Li ClassDecl->hasInheritedAssignment())
6651*67e74705SXin Li DeclareImplicitMoveAssignment(ClassDecl);
6652*67e74705SXin Li }
6653*67e74705SXin Li
6654*67e74705SXin Li if (ClassDecl->needsImplicitDestructor()) {
6655*67e74705SXin Li ++ASTContext::NumImplicitDestructors;
6656*67e74705SXin Li
6657*67e74705SXin Li // If we have a dynamic class, then the destructor may be virtual, so we
6658*67e74705SXin Li // have to declare the destructor immediately. This ensures that, e.g., it
6659*67e74705SXin Li // shows up in the right place in the vtable and that we diagnose problems
6660*67e74705SXin Li // with the implicit exception specification.
6661*67e74705SXin Li if (ClassDecl->isDynamicClass() ||
6662*67e74705SXin Li ClassDecl->needsOverloadResolutionForDestructor())
6663*67e74705SXin Li DeclareImplicitDestructor(ClassDecl);
6664*67e74705SXin Li }
6665*67e74705SXin Li }
6666*67e74705SXin Li
ActOnReenterTemplateScope(Scope * S,Decl * D)6667*67e74705SXin Li unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6668*67e74705SXin Li if (!D)
6669*67e74705SXin Li return 0;
6670*67e74705SXin Li
6671*67e74705SXin Li // The order of template parameters is not important here. All names
6672*67e74705SXin Li // get added to the same scope.
6673*67e74705SXin Li SmallVector<TemplateParameterList *, 4> ParameterLists;
6674*67e74705SXin Li
6675*67e74705SXin Li if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6676*67e74705SXin Li D = TD->getTemplatedDecl();
6677*67e74705SXin Li
6678*67e74705SXin Li if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6679*67e74705SXin Li ParameterLists.push_back(PSD->getTemplateParameters());
6680*67e74705SXin Li
6681*67e74705SXin Li if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6682*67e74705SXin Li for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6683*67e74705SXin Li ParameterLists.push_back(DD->getTemplateParameterList(i));
6684*67e74705SXin Li
6685*67e74705SXin Li if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6686*67e74705SXin Li if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6687*67e74705SXin Li ParameterLists.push_back(FTD->getTemplateParameters());
6688*67e74705SXin Li }
6689*67e74705SXin Li }
6690*67e74705SXin Li
6691*67e74705SXin Li if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6692*67e74705SXin Li for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6693*67e74705SXin Li ParameterLists.push_back(TD->getTemplateParameterList(i));
6694*67e74705SXin Li
6695*67e74705SXin Li if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6696*67e74705SXin Li if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6697*67e74705SXin Li ParameterLists.push_back(CTD->getTemplateParameters());
6698*67e74705SXin Li }
6699*67e74705SXin Li }
6700*67e74705SXin Li
6701*67e74705SXin Li unsigned Count = 0;
6702*67e74705SXin Li for (TemplateParameterList *Params : ParameterLists) {
6703*67e74705SXin Li if (Params->size() > 0)
6704*67e74705SXin Li // Ignore explicit specializations; they don't contribute to the template
6705*67e74705SXin Li // depth.
6706*67e74705SXin Li ++Count;
6707*67e74705SXin Li for (NamedDecl *Param : *Params) {
6708*67e74705SXin Li if (Param->getDeclName()) {
6709*67e74705SXin Li S->AddDecl(Param);
6710*67e74705SXin Li IdResolver.AddDecl(Param);
6711*67e74705SXin Li }
6712*67e74705SXin Li }
6713*67e74705SXin Li }
6714*67e74705SXin Li
6715*67e74705SXin Li return Count;
6716*67e74705SXin Li }
6717*67e74705SXin Li
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)6718*67e74705SXin Li void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6719*67e74705SXin Li if (!RecordD) return;
6720*67e74705SXin Li AdjustDeclIfTemplate(RecordD);
6721*67e74705SXin Li CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6722*67e74705SXin Li PushDeclContext(S, Record);
6723*67e74705SXin Li }
6724*67e74705SXin Li
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)6725*67e74705SXin Li void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6726*67e74705SXin Li if (!RecordD) return;
6727*67e74705SXin Li PopDeclContext();
6728*67e74705SXin Li }
6729*67e74705SXin Li
6730*67e74705SXin Li /// This is used to implement the constant expression evaluation part of the
6731*67e74705SXin Li /// attribute enable_if extension. There is nothing in standard C++ which would
6732*67e74705SXin Li /// require reentering parameters.
ActOnReenterCXXMethodParameter(Scope * S,ParmVarDecl * Param)6733*67e74705SXin Li void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6734*67e74705SXin Li if (!Param)
6735*67e74705SXin Li return;
6736*67e74705SXin Li
6737*67e74705SXin Li S->AddDecl(Param);
6738*67e74705SXin Li if (Param->getDeclName())
6739*67e74705SXin Li IdResolver.AddDecl(Param);
6740*67e74705SXin Li }
6741*67e74705SXin Li
6742*67e74705SXin Li /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6743*67e74705SXin Li /// parsing a top-level (non-nested) C++ class, and we are now
6744*67e74705SXin Li /// parsing those parts of the given Method declaration that could
6745*67e74705SXin Li /// not be parsed earlier (C++ [class.mem]p2), such as default
6746*67e74705SXin Li /// arguments. This action should enter the scope of the given
6747*67e74705SXin Li /// Method declaration as if we had just parsed the qualified method
6748*67e74705SXin Li /// name. However, it should not bring the parameters into scope;
6749*67e74705SXin Li /// that will be performed by ActOnDelayedCXXMethodParameter.
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)6750*67e74705SXin Li void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6751*67e74705SXin Li }
6752*67e74705SXin Li
6753*67e74705SXin Li /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6754*67e74705SXin Li /// C++ method declaration. We're (re-)introducing the given
6755*67e74705SXin Li /// function parameter into scope for use in parsing later parts of
6756*67e74705SXin Li /// the method declaration. For example, we could see an
6757*67e74705SXin Li /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)6758*67e74705SXin Li void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6759*67e74705SXin Li if (!ParamD)
6760*67e74705SXin Li return;
6761*67e74705SXin Li
6762*67e74705SXin Li ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6763*67e74705SXin Li
6764*67e74705SXin Li // If this parameter has an unparsed default argument, clear it out
6765*67e74705SXin Li // to make way for the parsed default argument.
6766*67e74705SXin Li if (Param->hasUnparsedDefaultArg())
6767*67e74705SXin Li Param->setDefaultArg(nullptr);
6768*67e74705SXin Li
6769*67e74705SXin Li S->AddDecl(Param);
6770*67e74705SXin Li if (Param->getDeclName())
6771*67e74705SXin Li IdResolver.AddDecl(Param);
6772*67e74705SXin Li }
6773*67e74705SXin Li
6774*67e74705SXin Li /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6775*67e74705SXin Li /// processing the delayed method declaration for Method. The method
6776*67e74705SXin Li /// declaration is now considered finished. There may be a separate
6777*67e74705SXin Li /// ActOnStartOfFunctionDef action later (not necessarily
6778*67e74705SXin Li /// immediately!) for this method, if it was also defined inside the
6779*67e74705SXin Li /// class body.
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)6780*67e74705SXin Li void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6781*67e74705SXin Li if (!MethodD)
6782*67e74705SXin Li return;
6783*67e74705SXin Li
6784*67e74705SXin Li AdjustDeclIfTemplate(MethodD);
6785*67e74705SXin Li
6786*67e74705SXin Li FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6787*67e74705SXin Li
6788*67e74705SXin Li // Now that we have our default arguments, check the constructor
6789*67e74705SXin Li // again. It could produce additional diagnostics or affect whether
6790*67e74705SXin Li // the class has implicitly-declared destructors, among other
6791*67e74705SXin Li // things.
6792*67e74705SXin Li if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6793*67e74705SXin Li CheckConstructor(Constructor);
6794*67e74705SXin Li
6795*67e74705SXin Li // Check the default arguments, which we may have added.
6796*67e74705SXin Li if (!Method->isInvalidDecl())
6797*67e74705SXin Li CheckCXXDefaultArguments(Method);
6798*67e74705SXin Li }
6799*67e74705SXin Li
6800*67e74705SXin Li /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6801*67e74705SXin Li /// the well-formedness of the constructor declarator @p D with type @p
6802*67e74705SXin Li /// R. If there are any errors in the declarator, this routine will
6803*67e74705SXin Li /// emit diagnostics and set the invalid bit to true. In any case, the type
6804*67e74705SXin Li /// will be updated to reflect a well-formed type for the constructor and
6805*67e74705SXin Li /// returned.
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)6806*67e74705SXin Li QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6807*67e74705SXin Li StorageClass &SC) {
6808*67e74705SXin Li bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6809*67e74705SXin Li
6810*67e74705SXin Li // C++ [class.ctor]p3:
6811*67e74705SXin Li // A constructor shall not be virtual (10.3) or static (9.4). A
6812*67e74705SXin Li // constructor can be invoked for a const, volatile or const
6813*67e74705SXin Li // volatile object. A constructor shall not be declared const,
6814*67e74705SXin Li // volatile, or const volatile (9.3.2).
6815*67e74705SXin Li if (isVirtual) {
6816*67e74705SXin Li if (!D.isInvalidType())
6817*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6818*67e74705SXin Li << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6819*67e74705SXin Li << SourceRange(D.getIdentifierLoc());
6820*67e74705SXin Li D.setInvalidType();
6821*67e74705SXin Li }
6822*67e74705SXin Li if (SC == SC_Static) {
6823*67e74705SXin Li if (!D.isInvalidType())
6824*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6825*67e74705SXin Li << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6826*67e74705SXin Li << SourceRange(D.getIdentifierLoc());
6827*67e74705SXin Li D.setInvalidType();
6828*67e74705SXin Li SC = SC_None;
6829*67e74705SXin Li }
6830*67e74705SXin Li
6831*67e74705SXin Li if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6832*67e74705SXin Li diagnoseIgnoredQualifiers(
6833*67e74705SXin Li diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6834*67e74705SXin Li D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6835*67e74705SXin Li D.getDeclSpec().getRestrictSpecLoc(),
6836*67e74705SXin Li D.getDeclSpec().getAtomicSpecLoc());
6837*67e74705SXin Li D.setInvalidType();
6838*67e74705SXin Li }
6839*67e74705SXin Li
6840*67e74705SXin Li DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6841*67e74705SXin Li if (FTI.TypeQuals != 0) {
6842*67e74705SXin Li if (FTI.TypeQuals & Qualifiers::Const)
6843*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6844*67e74705SXin Li << "const" << SourceRange(D.getIdentifierLoc());
6845*67e74705SXin Li if (FTI.TypeQuals & Qualifiers::Volatile)
6846*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6847*67e74705SXin Li << "volatile" << SourceRange(D.getIdentifierLoc());
6848*67e74705SXin Li if (FTI.TypeQuals & Qualifiers::Restrict)
6849*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6850*67e74705SXin Li << "restrict" << SourceRange(D.getIdentifierLoc());
6851*67e74705SXin Li D.setInvalidType();
6852*67e74705SXin Li }
6853*67e74705SXin Li
6854*67e74705SXin Li // C++0x [class.ctor]p4:
6855*67e74705SXin Li // A constructor shall not be declared with a ref-qualifier.
6856*67e74705SXin Li if (FTI.hasRefQualifier()) {
6857*67e74705SXin Li Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6858*67e74705SXin Li << FTI.RefQualifierIsLValueRef
6859*67e74705SXin Li << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6860*67e74705SXin Li D.setInvalidType();
6861*67e74705SXin Li }
6862*67e74705SXin Li
6863*67e74705SXin Li // Rebuild the function type "R" without any type qualifiers (in
6864*67e74705SXin Li // case any of the errors above fired) and with "void" as the
6865*67e74705SXin Li // return type, since constructors don't have return types.
6866*67e74705SXin Li const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6867*67e74705SXin Li if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6868*67e74705SXin Li return R;
6869*67e74705SXin Li
6870*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6871*67e74705SXin Li EPI.TypeQuals = 0;
6872*67e74705SXin Li EPI.RefQualifier = RQ_None;
6873*67e74705SXin Li
6874*67e74705SXin Li return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6875*67e74705SXin Li }
6876*67e74705SXin Li
6877*67e74705SXin Li /// CheckConstructor - Checks a fully-formed constructor for
6878*67e74705SXin Li /// well-formedness, issuing any diagnostics required. Returns true if
6879*67e74705SXin Li /// the constructor declarator is invalid.
CheckConstructor(CXXConstructorDecl * Constructor)6880*67e74705SXin Li void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6881*67e74705SXin Li CXXRecordDecl *ClassDecl
6882*67e74705SXin Li = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6883*67e74705SXin Li if (!ClassDecl)
6884*67e74705SXin Li return Constructor->setInvalidDecl();
6885*67e74705SXin Li
6886*67e74705SXin Li // C++ [class.copy]p3:
6887*67e74705SXin Li // A declaration of a constructor for a class X is ill-formed if
6888*67e74705SXin Li // its first parameter is of type (optionally cv-qualified) X and
6889*67e74705SXin Li // either there are no other parameters or else all other
6890*67e74705SXin Li // parameters have default arguments.
6891*67e74705SXin Li if (!Constructor->isInvalidDecl() &&
6892*67e74705SXin Li ((Constructor->getNumParams() == 1) ||
6893*67e74705SXin Li (Constructor->getNumParams() > 1 &&
6894*67e74705SXin Li Constructor->getParamDecl(1)->hasDefaultArg())) &&
6895*67e74705SXin Li Constructor->getTemplateSpecializationKind()
6896*67e74705SXin Li != TSK_ImplicitInstantiation) {
6897*67e74705SXin Li QualType ParamType = Constructor->getParamDecl(0)->getType();
6898*67e74705SXin Li QualType ClassTy = Context.getTagDeclType(ClassDecl);
6899*67e74705SXin Li if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6900*67e74705SXin Li SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6901*67e74705SXin Li const char *ConstRef
6902*67e74705SXin Li = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6903*67e74705SXin Li : " const &";
6904*67e74705SXin Li Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6905*67e74705SXin Li << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6906*67e74705SXin Li
6907*67e74705SXin Li // FIXME: Rather that making the constructor invalid, we should endeavor
6908*67e74705SXin Li // to fix the type.
6909*67e74705SXin Li Constructor->setInvalidDecl();
6910*67e74705SXin Li }
6911*67e74705SXin Li }
6912*67e74705SXin Li }
6913*67e74705SXin Li
6914*67e74705SXin Li /// CheckDestructor - Checks a fully-formed destructor definition for
6915*67e74705SXin Li /// well-formedness, issuing any diagnostics required. Returns true
6916*67e74705SXin Li /// on error.
CheckDestructor(CXXDestructorDecl * Destructor)6917*67e74705SXin Li bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6918*67e74705SXin Li CXXRecordDecl *RD = Destructor->getParent();
6919*67e74705SXin Li
6920*67e74705SXin Li if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6921*67e74705SXin Li SourceLocation Loc;
6922*67e74705SXin Li
6923*67e74705SXin Li if (!Destructor->isImplicit())
6924*67e74705SXin Li Loc = Destructor->getLocation();
6925*67e74705SXin Li else
6926*67e74705SXin Li Loc = RD->getLocation();
6927*67e74705SXin Li
6928*67e74705SXin Li // If we have a virtual destructor, look up the deallocation function
6929*67e74705SXin Li FunctionDecl *OperatorDelete = nullptr;
6930*67e74705SXin Li DeclarationName Name =
6931*67e74705SXin Li Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6932*67e74705SXin Li if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6933*67e74705SXin Li return true;
6934*67e74705SXin Li // If there's no class-specific operator delete, look up the global
6935*67e74705SXin Li // non-array delete.
6936*67e74705SXin Li if (!OperatorDelete)
6937*67e74705SXin Li OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6938*67e74705SXin Li
6939*67e74705SXin Li MarkFunctionReferenced(Loc, OperatorDelete);
6940*67e74705SXin Li
6941*67e74705SXin Li Destructor->setOperatorDelete(OperatorDelete);
6942*67e74705SXin Li }
6943*67e74705SXin Li
6944*67e74705SXin Li return false;
6945*67e74705SXin Li }
6946*67e74705SXin Li
6947*67e74705SXin Li /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6948*67e74705SXin Li /// the well-formednes of the destructor declarator @p D with type @p
6949*67e74705SXin Li /// R. If there are any errors in the declarator, this routine will
6950*67e74705SXin Li /// emit diagnostics and set the declarator to invalid. Even if this happens,
6951*67e74705SXin Li /// will be updated to reflect a well-formed type for the destructor and
6952*67e74705SXin Li /// returned.
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)6953*67e74705SXin Li QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6954*67e74705SXin Li StorageClass& SC) {
6955*67e74705SXin Li // C++ [class.dtor]p1:
6956*67e74705SXin Li // [...] A typedef-name that names a class is a class-name
6957*67e74705SXin Li // (7.1.3); however, a typedef-name that names a class shall not
6958*67e74705SXin Li // be used as the identifier in the declarator for a destructor
6959*67e74705SXin Li // declaration.
6960*67e74705SXin Li QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6961*67e74705SXin Li if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6962*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6963*67e74705SXin Li << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6964*67e74705SXin Li else if (const TemplateSpecializationType *TST =
6965*67e74705SXin Li DeclaratorType->getAs<TemplateSpecializationType>())
6966*67e74705SXin Li if (TST->isTypeAlias())
6967*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6968*67e74705SXin Li << DeclaratorType << 1;
6969*67e74705SXin Li
6970*67e74705SXin Li // C++ [class.dtor]p2:
6971*67e74705SXin Li // A destructor is used to destroy objects of its class type. A
6972*67e74705SXin Li // destructor takes no parameters, and no return type can be
6973*67e74705SXin Li // specified for it (not even void). The address of a destructor
6974*67e74705SXin Li // shall not be taken. A destructor shall not be static. A
6975*67e74705SXin Li // destructor can be invoked for a const, volatile or const
6976*67e74705SXin Li // volatile object. A destructor shall not be declared const,
6977*67e74705SXin Li // volatile or const volatile (9.3.2).
6978*67e74705SXin Li if (SC == SC_Static) {
6979*67e74705SXin Li if (!D.isInvalidType())
6980*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6981*67e74705SXin Li << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6982*67e74705SXin Li << SourceRange(D.getIdentifierLoc())
6983*67e74705SXin Li << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6984*67e74705SXin Li
6985*67e74705SXin Li SC = SC_None;
6986*67e74705SXin Li }
6987*67e74705SXin Li if (!D.isInvalidType()) {
6988*67e74705SXin Li // Destructors don't have return types, but the parser will
6989*67e74705SXin Li // happily parse something like:
6990*67e74705SXin Li //
6991*67e74705SXin Li // class X {
6992*67e74705SXin Li // float ~X();
6993*67e74705SXin Li // };
6994*67e74705SXin Li //
6995*67e74705SXin Li // The return type will be eliminated later.
6996*67e74705SXin Li if (D.getDeclSpec().hasTypeSpecifier())
6997*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6998*67e74705SXin Li << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6999*67e74705SXin Li << SourceRange(D.getIdentifierLoc());
7000*67e74705SXin Li else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7001*67e74705SXin Li diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7002*67e74705SXin Li SourceLocation(),
7003*67e74705SXin Li D.getDeclSpec().getConstSpecLoc(),
7004*67e74705SXin Li D.getDeclSpec().getVolatileSpecLoc(),
7005*67e74705SXin Li D.getDeclSpec().getRestrictSpecLoc(),
7006*67e74705SXin Li D.getDeclSpec().getAtomicSpecLoc());
7007*67e74705SXin Li D.setInvalidType();
7008*67e74705SXin Li }
7009*67e74705SXin Li }
7010*67e74705SXin Li
7011*67e74705SXin Li DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7012*67e74705SXin Li if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7013*67e74705SXin Li if (FTI.TypeQuals & Qualifiers::Const)
7014*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7015*67e74705SXin Li << "const" << SourceRange(D.getIdentifierLoc());
7016*67e74705SXin Li if (FTI.TypeQuals & Qualifiers::Volatile)
7017*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7018*67e74705SXin Li << "volatile" << SourceRange(D.getIdentifierLoc());
7019*67e74705SXin Li if (FTI.TypeQuals & Qualifiers::Restrict)
7020*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7021*67e74705SXin Li << "restrict" << SourceRange(D.getIdentifierLoc());
7022*67e74705SXin Li D.setInvalidType();
7023*67e74705SXin Li }
7024*67e74705SXin Li
7025*67e74705SXin Li // C++0x [class.dtor]p2:
7026*67e74705SXin Li // A destructor shall not be declared with a ref-qualifier.
7027*67e74705SXin Li if (FTI.hasRefQualifier()) {
7028*67e74705SXin Li Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7029*67e74705SXin Li << FTI.RefQualifierIsLValueRef
7030*67e74705SXin Li << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7031*67e74705SXin Li D.setInvalidType();
7032*67e74705SXin Li }
7033*67e74705SXin Li
7034*67e74705SXin Li // Make sure we don't have any parameters.
7035*67e74705SXin Li if (FTIHasNonVoidParameters(FTI)) {
7036*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7037*67e74705SXin Li
7038*67e74705SXin Li // Delete the parameters.
7039*67e74705SXin Li FTI.freeParams();
7040*67e74705SXin Li D.setInvalidType();
7041*67e74705SXin Li }
7042*67e74705SXin Li
7043*67e74705SXin Li // Make sure the destructor isn't variadic.
7044*67e74705SXin Li if (FTI.isVariadic) {
7045*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7046*67e74705SXin Li D.setInvalidType();
7047*67e74705SXin Li }
7048*67e74705SXin Li
7049*67e74705SXin Li // Rebuild the function type "R" without any type qualifiers or
7050*67e74705SXin Li // parameters (in case any of the errors above fired) and with
7051*67e74705SXin Li // "void" as the return type, since destructors don't have return
7052*67e74705SXin Li // types.
7053*67e74705SXin Li if (!D.isInvalidType())
7054*67e74705SXin Li return R;
7055*67e74705SXin Li
7056*67e74705SXin Li const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7057*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7058*67e74705SXin Li EPI.Variadic = false;
7059*67e74705SXin Li EPI.TypeQuals = 0;
7060*67e74705SXin Li EPI.RefQualifier = RQ_None;
7061*67e74705SXin Li return Context.getFunctionType(Context.VoidTy, None, EPI);
7062*67e74705SXin Li }
7063*67e74705SXin Li
extendLeft(SourceRange & R,SourceRange Before)7064*67e74705SXin Li static void extendLeft(SourceRange &R, SourceRange Before) {
7065*67e74705SXin Li if (Before.isInvalid())
7066*67e74705SXin Li return;
7067*67e74705SXin Li R.setBegin(Before.getBegin());
7068*67e74705SXin Li if (R.getEnd().isInvalid())
7069*67e74705SXin Li R.setEnd(Before.getEnd());
7070*67e74705SXin Li }
7071*67e74705SXin Li
extendRight(SourceRange & R,SourceRange After)7072*67e74705SXin Li static void extendRight(SourceRange &R, SourceRange After) {
7073*67e74705SXin Li if (After.isInvalid())
7074*67e74705SXin Li return;
7075*67e74705SXin Li if (R.getBegin().isInvalid())
7076*67e74705SXin Li R.setBegin(After.getBegin());
7077*67e74705SXin Li R.setEnd(After.getEnd());
7078*67e74705SXin Li }
7079*67e74705SXin Li
7080*67e74705SXin Li /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7081*67e74705SXin Li /// well-formednes of the conversion function declarator @p D with
7082*67e74705SXin Li /// type @p R. If there are any errors in the declarator, this routine
7083*67e74705SXin Li /// will emit diagnostics and return true. Otherwise, it will return
7084*67e74705SXin Li /// false. Either way, the type @p R will be updated to reflect a
7085*67e74705SXin Li /// well-formed type for the conversion operator.
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)7086*67e74705SXin Li void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7087*67e74705SXin Li StorageClass& SC) {
7088*67e74705SXin Li // C++ [class.conv.fct]p1:
7089*67e74705SXin Li // Neither parameter types nor return type can be specified. The
7090*67e74705SXin Li // type of a conversion function (8.3.5) is "function taking no
7091*67e74705SXin Li // parameter returning conversion-type-id."
7092*67e74705SXin Li if (SC == SC_Static) {
7093*67e74705SXin Li if (!D.isInvalidType())
7094*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7095*67e74705SXin Li << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7096*67e74705SXin Li << D.getName().getSourceRange();
7097*67e74705SXin Li D.setInvalidType();
7098*67e74705SXin Li SC = SC_None;
7099*67e74705SXin Li }
7100*67e74705SXin Li
7101*67e74705SXin Li TypeSourceInfo *ConvTSI = nullptr;
7102*67e74705SXin Li QualType ConvType =
7103*67e74705SXin Li GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7104*67e74705SXin Li
7105*67e74705SXin Li if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7106*67e74705SXin Li // Conversion functions don't have return types, but the parser will
7107*67e74705SXin Li // happily parse something like:
7108*67e74705SXin Li //
7109*67e74705SXin Li // class X {
7110*67e74705SXin Li // float operator bool();
7111*67e74705SXin Li // };
7112*67e74705SXin Li //
7113*67e74705SXin Li // The return type will be changed later anyway.
7114*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7115*67e74705SXin Li << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7116*67e74705SXin Li << SourceRange(D.getIdentifierLoc());
7117*67e74705SXin Li D.setInvalidType();
7118*67e74705SXin Li }
7119*67e74705SXin Li
7120*67e74705SXin Li const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7121*67e74705SXin Li
7122*67e74705SXin Li // Make sure we don't have any parameters.
7123*67e74705SXin Li if (Proto->getNumParams() > 0) {
7124*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7125*67e74705SXin Li
7126*67e74705SXin Li // Delete the parameters.
7127*67e74705SXin Li D.getFunctionTypeInfo().freeParams();
7128*67e74705SXin Li D.setInvalidType();
7129*67e74705SXin Li } else if (Proto->isVariadic()) {
7130*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7131*67e74705SXin Li D.setInvalidType();
7132*67e74705SXin Li }
7133*67e74705SXin Li
7134*67e74705SXin Li // Diagnose "&operator bool()" and other such nonsense. This
7135*67e74705SXin Li // is actually a gcc extension which we don't support.
7136*67e74705SXin Li if (Proto->getReturnType() != ConvType) {
7137*67e74705SXin Li bool NeedsTypedef = false;
7138*67e74705SXin Li SourceRange Before, After;
7139*67e74705SXin Li
7140*67e74705SXin Li // Walk the chunks and extract information on them for our diagnostic.
7141*67e74705SXin Li bool PastFunctionChunk = false;
7142*67e74705SXin Li for (auto &Chunk : D.type_objects()) {
7143*67e74705SXin Li switch (Chunk.Kind) {
7144*67e74705SXin Li case DeclaratorChunk::Function:
7145*67e74705SXin Li if (!PastFunctionChunk) {
7146*67e74705SXin Li if (Chunk.Fun.HasTrailingReturnType) {
7147*67e74705SXin Li TypeSourceInfo *TRT = nullptr;
7148*67e74705SXin Li GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7149*67e74705SXin Li if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7150*67e74705SXin Li }
7151*67e74705SXin Li PastFunctionChunk = true;
7152*67e74705SXin Li break;
7153*67e74705SXin Li }
7154*67e74705SXin Li // Fall through.
7155*67e74705SXin Li case DeclaratorChunk::Array:
7156*67e74705SXin Li NeedsTypedef = true;
7157*67e74705SXin Li extendRight(After, Chunk.getSourceRange());
7158*67e74705SXin Li break;
7159*67e74705SXin Li
7160*67e74705SXin Li case DeclaratorChunk::Pointer:
7161*67e74705SXin Li case DeclaratorChunk::BlockPointer:
7162*67e74705SXin Li case DeclaratorChunk::Reference:
7163*67e74705SXin Li case DeclaratorChunk::MemberPointer:
7164*67e74705SXin Li case DeclaratorChunk::Pipe:
7165*67e74705SXin Li extendLeft(Before, Chunk.getSourceRange());
7166*67e74705SXin Li break;
7167*67e74705SXin Li
7168*67e74705SXin Li case DeclaratorChunk::Paren:
7169*67e74705SXin Li extendLeft(Before, Chunk.Loc);
7170*67e74705SXin Li extendRight(After, Chunk.EndLoc);
7171*67e74705SXin Li break;
7172*67e74705SXin Li }
7173*67e74705SXin Li }
7174*67e74705SXin Li
7175*67e74705SXin Li SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7176*67e74705SXin Li After.isValid() ? After.getBegin() :
7177*67e74705SXin Li D.getIdentifierLoc();
7178*67e74705SXin Li auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7179*67e74705SXin Li DB << Before << After;
7180*67e74705SXin Li
7181*67e74705SXin Li if (!NeedsTypedef) {
7182*67e74705SXin Li DB << /*don't need a typedef*/0;
7183*67e74705SXin Li
7184*67e74705SXin Li // If we can provide a correct fix-it hint, do so.
7185*67e74705SXin Li if (After.isInvalid() && ConvTSI) {
7186*67e74705SXin Li SourceLocation InsertLoc =
7187*67e74705SXin Li getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7188*67e74705SXin Li DB << FixItHint::CreateInsertion(InsertLoc, " ")
7189*67e74705SXin Li << FixItHint::CreateInsertionFromRange(
7190*67e74705SXin Li InsertLoc, CharSourceRange::getTokenRange(Before))
7191*67e74705SXin Li << FixItHint::CreateRemoval(Before);
7192*67e74705SXin Li }
7193*67e74705SXin Li } else if (!Proto->getReturnType()->isDependentType()) {
7194*67e74705SXin Li DB << /*typedef*/1 << Proto->getReturnType();
7195*67e74705SXin Li } else if (getLangOpts().CPlusPlus11) {
7196*67e74705SXin Li DB << /*alias template*/2 << Proto->getReturnType();
7197*67e74705SXin Li } else {
7198*67e74705SXin Li DB << /*might not be fixable*/3;
7199*67e74705SXin Li }
7200*67e74705SXin Li
7201*67e74705SXin Li // Recover by incorporating the other type chunks into the result type.
7202*67e74705SXin Li // Note, this does *not* change the name of the function. This is compatible
7203*67e74705SXin Li // with the GCC extension:
7204*67e74705SXin Li // struct S { &operator int(); } s;
7205*67e74705SXin Li // int &r = s.operator int(); // ok in GCC
7206*67e74705SXin Li // S::operator int&() {} // error in GCC, function name is 'operator int'.
7207*67e74705SXin Li ConvType = Proto->getReturnType();
7208*67e74705SXin Li }
7209*67e74705SXin Li
7210*67e74705SXin Li // C++ [class.conv.fct]p4:
7211*67e74705SXin Li // The conversion-type-id shall not represent a function type nor
7212*67e74705SXin Li // an array type.
7213*67e74705SXin Li if (ConvType->isArrayType()) {
7214*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7215*67e74705SXin Li ConvType = Context.getPointerType(ConvType);
7216*67e74705SXin Li D.setInvalidType();
7217*67e74705SXin Li } else if (ConvType->isFunctionType()) {
7218*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7219*67e74705SXin Li ConvType = Context.getPointerType(ConvType);
7220*67e74705SXin Li D.setInvalidType();
7221*67e74705SXin Li }
7222*67e74705SXin Li
7223*67e74705SXin Li // Rebuild the function type "R" without any parameters (in case any
7224*67e74705SXin Li // of the errors above fired) and with the conversion type as the
7225*67e74705SXin Li // return type.
7226*67e74705SXin Li if (D.isInvalidType())
7227*67e74705SXin Li R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7228*67e74705SXin Li
7229*67e74705SXin Li // C++0x explicit conversion operators.
7230*67e74705SXin Li if (D.getDeclSpec().isExplicitSpecified())
7231*67e74705SXin Li Diag(D.getDeclSpec().getExplicitSpecLoc(),
7232*67e74705SXin Li getLangOpts().CPlusPlus11 ?
7233*67e74705SXin Li diag::warn_cxx98_compat_explicit_conversion_functions :
7234*67e74705SXin Li diag::ext_explicit_conversion_functions)
7235*67e74705SXin Li << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7236*67e74705SXin Li }
7237*67e74705SXin Li
7238*67e74705SXin Li /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7239*67e74705SXin Li /// the declaration of the given C++ conversion function. This routine
7240*67e74705SXin Li /// is responsible for recording the conversion function in the C++
7241*67e74705SXin Li /// class, if possible.
ActOnConversionDeclarator(CXXConversionDecl * Conversion)7242*67e74705SXin Li Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7243*67e74705SXin Li assert(Conversion && "Expected to receive a conversion function declaration");
7244*67e74705SXin Li
7245*67e74705SXin Li CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7246*67e74705SXin Li
7247*67e74705SXin Li // Make sure we aren't redeclaring the conversion function.
7248*67e74705SXin Li QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7249*67e74705SXin Li
7250*67e74705SXin Li // C++ [class.conv.fct]p1:
7251*67e74705SXin Li // [...] A conversion function is never used to convert a
7252*67e74705SXin Li // (possibly cv-qualified) object to the (possibly cv-qualified)
7253*67e74705SXin Li // same object type (or a reference to it), to a (possibly
7254*67e74705SXin Li // cv-qualified) base class of that type (or a reference to it),
7255*67e74705SXin Li // or to (possibly cv-qualified) void.
7256*67e74705SXin Li // FIXME: Suppress this warning if the conversion function ends up being a
7257*67e74705SXin Li // virtual function that overrides a virtual function in a base class.
7258*67e74705SXin Li QualType ClassType
7259*67e74705SXin Li = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7260*67e74705SXin Li if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7261*67e74705SXin Li ConvType = ConvTypeRef->getPointeeType();
7262*67e74705SXin Li if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7263*67e74705SXin Li Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7264*67e74705SXin Li /* Suppress diagnostics for instantiations. */;
7265*67e74705SXin Li else if (ConvType->isRecordType()) {
7266*67e74705SXin Li ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7267*67e74705SXin Li if (ConvType == ClassType)
7268*67e74705SXin Li Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7269*67e74705SXin Li << ClassType;
7270*67e74705SXin Li else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
7271*67e74705SXin Li Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7272*67e74705SXin Li << ClassType << ConvType;
7273*67e74705SXin Li } else if (ConvType->isVoidType()) {
7274*67e74705SXin Li Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7275*67e74705SXin Li << ClassType << ConvType;
7276*67e74705SXin Li }
7277*67e74705SXin Li
7278*67e74705SXin Li if (FunctionTemplateDecl *ConversionTemplate
7279*67e74705SXin Li = Conversion->getDescribedFunctionTemplate())
7280*67e74705SXin Li return ConversionTemplate;
7281*67e74705SXin Li
7282*67e74705SXin Li return Conversion;
7283*67e74705SXin Li }
7284*67e74705SXin Li
7285*67e74705SXin Li //===----------------------------------------------------------------------===//
7286*67e74705SXin Li // Namespace Handling
7287*67e74705SXin Li //===----------------------------------------------------------------------===//
7288*67e74705SXin Li
7289*67e74705SXin Li /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7290*67e74705SXin Li /// reopened.
DiagnoseNamespaceInlineMismatch(Sema & S,SourceLocation KeywordLoc,SourceLocation Loc,IdentifierInfo * II,bool * IsInline,NamespaceDecl * PrevNS)7291*67e74705SXin Li static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7292*67e74705SXin Li SourceLocation Loc,
7293*67e74705SXin Li IdentifierInfo *II, bool *IsInline,
7294*67e74705SXin Li NamespaceDecl *PrevNS) {
7295*67e74705SXin Li assert(*IsInline != PrevNS->isInline());
7296*67e74705SXin Li
7297*67e74705SXin Li // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7298*67e74705SXin Li // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7299*67e74705SXin Li // inline namespaces, with the intention of bringing names into namespace std.
7300*67e74705SXin Li //
7301*67e74705SXin Li // We support this just well enough to get that case working; this is not
7302*67e74705SXin Li // sufficient to support reopening namespaces as inline in general.
7303*67e74705SXin Li if (*IsInline && II && II->getName().startswith("__atomic") &&
7304*67e74705SXin Li S.getSourceManager().isInSystemHeader(Loc)) {
7305*67e74705SXin Li // Mark all prior declarations of the namespace as inline.
7306*67e74705SXin Li for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7307*67e74705SXin Li NS = NS->getPreviousDecl())
7308*67e74705SXin Li NS->setInline(*IsInline);
7309*67e74705SXin Li // Patch up the lookup table for the containing namespace. This isn't really
7310*67e74705SXin Li // correct, but it's good enough for this particular case.
7311*67e74705SXin Li for (auto *I : PrevNS->decls())
7312*67e74705SXin Li if (auto *ND = dyn_cast<NamedDecl>(I))
7313*67e74705SXin Li PrevNS->getParent()->makeDeclVisibleInContext(ND);
7314*67e74705SXin Li return;
7315*67e74705SXin Li }
7316*67e74705SXin Li
7317*67e74705SXin Li if (PrevNS->isInline())
7318*67e74705SXin Li // The user probably just forgot the 'inline', so suggest that it
7319*67e74705SXin Li // be added back.
7320*67e74705SXin Li S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7321*67e74705SXin Li << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7322*67e74705SXin Li else
7323*67e74705SXin Li S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7324*67e74705SXin Li
7325*67e74705SXin Li S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7326*67e74705SXin Li *IsInline = PrevNS->isInline();
7327*67e74705SXin Li }
7328*67e74705SXin Li
7329*67e74705SXin Li /// ActOnStartNamespaceDef - This is called at the start of a namespace
7330*67e74705SXin Li /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,AttributeList * AttrList,UsingDirectiveDecl * & UD)7331*67e74705SXin Li Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7332*67e74705SXin Li SourceLocation InlineLoc,
7333*67e74705SXin Li SourceLocation NamespaceLoc,
7334*67e74705SXin Li SourceLocation IdentLoc,
7335*67e74705SXin Li IdentifierInfo *II,
7336*67e74705SXin Li SourceLocation LBrace,
7337*67e74705SXin Li AttributeList *AttrList,
7338*67e74705SXin Li UsingDirectiveDecl *&UD) {
7339*67e74705SXin Li SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7340*67e74705SXin Li // For anonymous namespace, take the location of the left brace.
7341*67e74705SXin Li SourceLocation Loc = II ? IdentLoc : LBrace;
7342*67e74705SXin Li bool IsInline = InlineLoc.isValid();
7343*67e74705SXin Li bool IsInvalid = false;
7344*67e74705SXin Li bool IsStd = false;
7345*67e74705SXin Li bool AddToKnown = false;
7346*67e74705SXin Li Scope *DeclRegionScope = NamespcScope->getParent();
7347*67e74705SXin Li
7348*67e74705SXin Li NamespaceDecl *PrevNS = nullptr;
7349*67e74705SXin Li if (II) {
7350*67e74705SXin Li // C++ [namespace.def]p2:
7351*67e74705SXin Li // The identifier in an original-namespace-definition shall not
7352*67e74705SXin Li // have been previously defined in the declarative region in
7353*67e74705SXin Li // which the original-namespace-definition appears. The
7354*67e74705SXin Li // identifier in an original-namespace-definition is the name of
7355*67e74705SXin Li // the namespace. Subsequently in that declarative region, it is
7356*67e74705SXin Li // treated as an original-namespace-name.
7357*67e74705SXin Li //
7358*67e74705SXin Li // Since namespace names are unique in their scope, and we don't
7359*67e74705SXin Li // look through using directives, just look for any ordinary names
7360*67e74705SXin Li // as if by qualified name lookup.
7361*67e74705SXin Li LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7362*67e74705SXin Li LookupQualifiedName(R, CurContext->getRedeclContext());
7363*67e74705SXin Li NamedDecl *PrevDecl =
7364*67e74705SXin Li R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
7365*67e74705SXin Li PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7366*67e74705SXin Li
7367*67e74705SXin Li if (PrevNS) {
7368*67e74705SXin Li // This is an extended namespace definition.
7369*67e74705SXin Li if (IsInline != PrevNS->isInline())
7370*67e74705SXin Li DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7371*67e74705SXin Li &IsInline, PrevNS);
7372*67e74705SXin Li } else if (PrevDecl) {
7373*67e74705SXin Li // This is an invalid name redefinition.
7374*67e74705SXin Li Diag(Loc, diag::err_redefinition_different_kind)
7375*67e74705SXin Li << II;
7376*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7377*67e74705SXin Li IsInvalid = true;
7378*67e74705SXin Li // Continue on to push Namespc as current DeclContext and return it.
7379*67e74705SXin Li } else if (II->isStr("std") &&
7380*67e74705SXin Li CurContext->getRedeclContext()->isTranslationUnit()) {
7381*67e74705SXin Li // This is the first "real" definition of the namespace "std", so update
7382*67e74705SXin Li // our cache of the "std" namespace to point at this definition.
7383*67e74705SXin Li PrevNS = getStdNamespace();
7384*67e74705SXin Li IsStd = true;
7385*67e74705SXin Li AddToKnown = !IsInline;
7386*67e74705SXin Li } else {
7387*67e74705SXin Li // We've seen this namespace for the first time.
7388*67e74705SXin Li AddToKnown = !IsInline;
7389*67e74705SXin Li }
7390*67e74705SXin Li } else {
7391*67e74705SXin Li // Anonymous namespaces.
7392*67e74705SXin Li
7393*67e74705SXin Li // Determine whether the parent already has an anonymous namespace.
7394*67e74705SXin Li DeclContext *Parent = CurContext->getRedeclContext();
7395*67e74705SXin Li if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7396*67e74705SXin Li PrevNS = TU->getAnonymousNamespace();
7397*67e74705SXin Li } else {
7398*67e74705SXin Li NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7399*67e74705SXin Li PrevNS = ND->getAnonymousNamespace();
7400*67e74705SXin Li }
7401*67e74705SXin Li
7402*67e74705SXin Li if (PrevNS && IsInline != PrevNS->isInline())
7403*67e74705SXin Li DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7404*67e74705SXin Li &IsInline, PrevNS);
7405*67e74705SXin Li }
7406*67e74705SXin Li
7407*67e74705SXin Li NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7408*67e74705SXin Li StartLoc, Loc, II, PrevNS);
7409*67e74705SXin Li if (IsInvalid)
7410*67e74705SXin Li Namespc->setInvalidDecl();
7411*67e74705SXin Li
7412*67e74705SXin Li ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7413*67e74705SXin Li
7414*67e74705SXin Li // FIXME: Should we be merging attributes?
7415*67e74705SXin Li if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7416*67e74705SXin Li PushNamespaceVisibilityAttr(Attr, Loc);
7417*67e74705SXin Li
7418*67e74705SXin Li if (IsStd)
7419*67e74705SXin Li StdNamespace = Namespc;
7420*67e74705SXin Li if (AddToKnown)
7421*67e74705SXin Li KnownNamespaces[Namespc] = false;
7422*67e74705SXin Li
7423*67e74705SXin Li if (II) {
7424*67e74705SXin Li PushOnScopeChains(Namespc, DeclRegionScope);
7425*67e74705SXin Li } else {
7426*67e74705SXin Li // Link the anonymous namespace into its parent.
7427*67e74705SXin Li DeclContext *Parent = CurContext->getRedeclContext();
7428*67e74705SXin Li if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7429*67e74705SXin Li TU->setAnonymousNamespace(Namespc);
7430*67e74705SXin Li } else {
7431*67e74705SXin Li cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7432*67e74705SXin Li }
7433*67e74705SXin Li
7434*67e74705SXin Li CurContext->addDecl(Namespc);
7435*67e74705SXin Li
7436*67e74705SXin Li // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7437*67e74705SXin Li // behaves as if it were replaced by
7438*67e74705SXin Li // namespace unique { /* empty body */ }
7439*67e74705SXin Li // using namespace unique;
7440*67e74705SXin Li // namespace unique { namespace-body }
7441*67e74705SXin Li // where all occurrences of 'unique' in a translation unit are
7442*67e74705SXin Li // replaced by the same identifier and this identifier differs
7443*67e74705SXin Li // from all other identifiers in the entire program.
7444*67e74705SXin Li
7445*67e74705SXin Li // We just create the namespace with an empty name and then add an
7446*67e74705SXin Li // implicit using declaration, just like the standard suggests.
7447*67e74705SXin Li //
7448*67e74705SXin Li // CodeGen enforces the "universally unique" aspect by giving all
7449*67e74705SXin Li // declarations semantically contained within an anonymous
7450*67e74705SXin Li // namespace internal linkage.
7451*67e74705SXin Li
7452*67e74705SXin Li if (!PrevNS) {
7453*67e74705SXin Li UD = UsingDirectiveDecl::Create(Context, Parent,
7454*67e74705SXin Li /* 'using' */ LBrace,
7455*67e74705SXin Li /* 'namespace' */ SourceLocation(),
7456*67e74705SXin Li /* qualifier */ NestedNameSpecifierLoc(),
7457*67e74705SXin Li /* identifier */ SourceLocation(),
7458*67e74705SXin Li Namespc,
7459*67e74705SXin Li /* Ancestor */ Parent);
7460*67e74705SXin Li UD->setImplicit();
7461*67e74705SXin Li Parent->addDecl(UD);
7462*67e74705SXin Li }
7463*67e74705SXin Li }
7464*67e74705SXin Li
7465*67e74705SXin Li ActOnDocumentableDecl(Namespc);
7466*67e74705SXin Li
7467*67e74705SXin Li // Although we could have an invalid decl (i.e. the namespace name is a
7468*67e74705SXin Li // redefinition), push it as current DeclContext and try to continue parsing.
7469*67e74705SXin Li // FIXME: We should be able to push Namespc here, so that the each DeclContext
7470*67e74705SXin Li // for the namespace has the declarations that showed up in that particular
7471*67e74705SXin Li // namespace definition.
7472*67e74705SXin Li PushDeclContext(NamespcScope, Namespc);
7473*67e74705SXin Li return Namespc;
7474*67e74705SXin Li }
7475*67e74705SXin Li
7476*67e74705SXin Li /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7477*67e74705SXin Li /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)7478*67e74705SXin Li static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7479*67e74705SXin Li if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7480*67e74705SXin Li return AD->getNamespace();
7481*67e74705SXin Li return dyn_cast_or_null<NamespaceDecl>(D);
7482*67e74705SXin Li }
7483*67e74705SXin Li
7484*67e74705SXin Li /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7485*67e74705SXin Li /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)7486*67e74705SXin Li void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7487*67e74705SXin Li NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7488*67e74705SXin Li assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7489*67e74705SXin Li Namespc->setRBraceLoc(RBrace);
7490*67e74705SXin Li PopDeclContext();
7491*67e74705SXin Li if (Namespc->hasAttr<VisibilityAttr>())
7492*67e74705SXin Li PopPragmaVisibility(true, RBrace);
7493*67e74705SXin Li }
7494*67e74705SXin Li
getStdBadAlloc() const7495*67e74705SXin Li CXXRecordDecl *Sema::getStdBadAlloc() const {
7496*67e74705SXin Li return cast_or_null<CXXRecordDecl>(
7497*67e74705SXin Li StdBadAlloc.get(Context.getExternalSource()));
7498*67e74705SXin Li }
7499*67e74705SXin Li
getStdNamespace() const7500*67e74705SXin Li NamespaceDecl *Sema::getStdNamespace() const {
7501*67e74705SXin Li return cast_or_null<NamespaceDecl>(
7502*67e74705SXin Li StdNamespace.get(Context.getExternalSource()));
7503*67e74705SXin Li }
7504*67e74705SXin Li
7505*67e74705SXin Li /// \brief Retrieve the special "std" namespace, which may require us to
7506*67e74705SXin Li /// implicitly define the namespace.
getOrCreateStdNamespace()7507*67e74705SXin Li NamespaceDecl *Sema::getOrCreateStdNamespace() {
7508*67e74705SXin Li if (!StdNamespace) {
7509*67e74705SXin Li // The "std" namespace has not yet been defined, so build one implicitly.
7510*67e74705SXin Li StdNamespace = NamespaceDecl::Create(Context,
7511*67e74705SXin Li Context.getTranslationUnitDecl(),
7512*67e74705SXin Li /*Inline=*/false,
7513*67e74705SXin Li SourceLocation(), SourceLocation(),
7514*67e74705SXin Li &PP.getIdentifierTable().get("std"),
7515*67e74705SXin Li /*PrevDecl=*/nullptr);
7516*67e74705SXin Li getStdNamespace()->setImplicit(true);
7517*67e74705SXin Li }
7518*67e74705SXin Li
7519*67e74705SXin Li return getStdNamespace();
7520*67e74705SXin Li }
7521*67e74705SXin Li
isStdInitializerList(QualType Ty,QualType * Element)7522*67e74705SXin Li bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7523*67e74705SXin Li assert(getLangOpts().CPlusPlus &&
7524*67e74705SXin Li "Looking for std::initializer_list outside of C++.");
7525*67e74705SXin Li
7526*67e74705SXin Li // We're looking for implicit instantiations of
7527*67e74705SXin Li // template <typename E> class std::initializer_list.
7528*67e74705SXin Li
7529*67e74705SXin Li if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7530*67e74705SXin Li return false;
7531*67e74705SXin Li
7532*67e74705SXin Li ClassTemplateDecl *Template = nullptr;
7533*67e74705SXin Li const TemplateArgument *Arguments = nullptr;
7534*67e74705SXin Li
7535*67e74705SXin Li if (const RecordType *RT = Ty->getAs<RecordType>()) {
7536*67e74705SXin Li
7537*67e74705SXin Li ClassTemplateSpecializationDecl *Specialization =
7538*67e74705SXin Li dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7539*67e74705SXin Li if (!Specialization)
7540*67e74705SXin Li return false;
7541*67e74705SXin Li
7542*67e74705SXin Li Template = Specialization->getSpecializedTemplate();
7543*67e74705SXin Li Arguments = Specialization->getTemplateArgs().data();
7544*67e74705SXin Li } else if (const TemplateSpecializationType *TST =
7545*67e74705SXin Li Ty->getAs<TemplateSpecializationType>()) {
7546*67e74705SXin Li Template = dyn_cast_or_null<ClassTemplateDecl>(
7547*67e74705SXin Li TST->getTemplateName().getAsTemplateDecl());
7548*67e74705SXin Li Arguments = TST->getArgs();
7549*67e74705SXin Li }
7550*67e74705SXin Li if (!Template)
7551*67e74705SXin Li return false;
7552*67e74705SXin Li
7553*67e74705SXin Li if (!StdInitializerList) {
7554*67e74705SXin Li // Haven't recognized std::initializer_list yet, maybe this is it.
7555*67e74705SXin Li CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7556*67e74705SXin Li if (TemplateClass->getIdentifier() !=
7557*67e74705SXin Li &PP.getIdentifierTable().get("initializer_list") ||
7558*67e74705SXin Li !getStdNamespace()->InEnclosingNamespaceSetOf(
7559*67e74705SXin Li TemplateClass->getDeclContext()))
7560*67e74705SXin Li return false;
7561*67e74705SXin Li // This is a template called std::initializer_list, but is it the right
7562*67e74705SXin Li // template?
7563*67e74705SXin Li TemplateParameterList *Params = Template->getTemplateParameters();
7564*67e74705SXin Li if (Params->getMinRequiredArguments() != 1)
7565*67e74705SXin Li return false;
7566*67e74705SXin Li if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7567*67e74705SXin Li return false;
7568*67e74705SXin Li
7569*67e74705SXin Li // It's the right template.
7570*67e74705SXin Li StdInitializerList = Template;
7571*67e74705SXin Li }
7572*67e74705SXin Li
7573*67e74705SXin Li if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7574*67e74705SXin Li return false;
7575*67e74705SXin Li
7576*67e74705SXin Li // This is an instance of std::initializer_list. Find the argument type.
7577*67e74705SXin Li if (Element)
7578*67e74705SXin Li *Element = Arguments[0].getAsType();
7579*67e74705SXin Li return true;
7580*67e74705SXin Li }
7581*67e74705SXin Li
LookupStdInitializerList(Sema & S,SourceLocation Loc)7582*67e74705SXin Li static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7583*67e74705SXin Li NamespaceDecl *Std = S.getStdNamespace();
7584*67e74705SXin Li if (!Std) {
7585*67e74705SXin Li S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7586*67e74705SXin Li return nullptr;
7587*67e74705SXin Li }
7588*67e74705SXin Li
7589*67e74705SXin Li LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7590*67e74705SXin Li Loc, Sema::LookupOrdinaryName);
7591*67e74705SXin Li if (!S.LookupQualifiedName(Result, Std)) {
7592*67e74705SXin Li S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7593*67e74705SXin Li return nullptr;
7594*67e74705SXin Li }
7595*67e74705SXin Li ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7596*67e74705SXin Li if (!Template) {
7597*67e74705SXin Li Result.suppressDiagnostics();
7598*67e74705SXin Li // We found something weird. Complain about the first thing we found.
7599*67e74705SXin Li NamedDecl *Found = *Result.begin();
7600*67e74705SXin Li S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7601*67e74705SXin Li return nullptr;
7602*67e74705SXin Li }
7603*67e74705SXin Li
7604*67e74705SXin Li // We found some template called std::initializer_list. Now verify that it's
7605*67e74705SXin Li // correct.
7606*67e74705SXin Li TemplateParameterList *Params = Template->getTemplateParameters();
7607*67e74705SXin Li if (Params->getMinRequiredArguments() != 1 ||
7608*67e74705SXin Li !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7609*67e74705SXin Li S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7610*67e74705SXin Li return nullptr;
7611*67e74705SXin Li }
7612*67e74705SXin Li
7613*67e74705SXin Li return Template;
7614*67e74705SXin Li }
7615*67e74705SXin Li
BuildStdInitializerList(QualType Element,SourceLocation Loc)7616*67e74705SXin Li QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7617*67e74705SXin Li if (!StdInitializerList) {
7618*67e74705SXin Li StdInitializerList = LookupStdInitializerList(*this, Loc);
7619*67e74705SXin Li if (!StdInitializerList)
7620*67e74705SXin Li return QualType();
7621*67e74705SXin Li }
7622*67e74705SXin Li
7623*67e74705SXin Li TemplateArgumentListInfo Args(Loc, Loc);
7624*67e74705SXin Li Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7625*67e74705SXin Li Context.getTrivialTypeSourceInfo(Element,
7626*67e74705SXin Li Loc)));
7627*67e74705SXin Li return Context.getCanonicalType(
7628*67e74705SXin Li CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7629*67e74705SXin Li }
7630*67e74705SXin Li
isInitListConstructor(const CXXConstructorDecl * Ctor)7631*67e74705SXin Li bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7632*67e74705SXin Li // C++ [dcl.init.list]p2:
7633*67e74705SXin Li // A constructor is an initializer-list constructor if its first parameter
7634*67e74705SXin Li // is of type std::initializer_list<E> or reference to possibly cv-qualified
7635*67e74705SXin Li // std::initializer_list<E> for some type E, and either there are no other
7636*67e74705SXin Li // parameters or else all other parameters have default arguments.
7637*67e74705SXin Li if (Ctor->getNumParams() < 1 ||
7638*67e74705SXin Li (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7639*67e74705SXin Li return false;
7640*67e74705SXin Li
7641*67e74705SXin Li QualType ArgType = Ctor->getParamDecl(0)->getType();
7642*67e74705SXin Li if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7643*67e74705SXin Li ArgType = RT->getPointeeType().getUnqualifiedType();
7644*67e74705SXin Li
7645*67e74705SXin Li return isStdInitializerList(ArgType, nullptr);
7646*67e74705SXin Li }
7647*67e74705SXin Li
7648*67e74705SXin Li /// \brief Determine whether a using statement is in a context where it will be
7649*67e74705SXin Li /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)7650*67e74705SXin Li static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7651*67e74705SXin Li switch (CurContext->getDeclKind()) {
7652*67e74705SXin Li case Decl::TranslationUnit:
7653*67e74705SXin Li return true;
7654*67e74705SXin Li case Decl::LinkageSpec:
7655*67e74705SXin Li return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7656*67e74705SXin Li default:
7657*67e74705SXin Li return false;
7658*67e74705SXin Li }
7659*67e74705SXin Li }
7660*67e74705SXin Li
7661*67e74705SXin Li namespace {
7662*67e74705SXin Li
7663*67e74705SXin Li // Callback to only accept typo corrections that are namespaces.
7664*67e74705SXin Li class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7665*67e74705SXin Li public:
ValidateCandidate(const TypoCorrection & candidate)7666*67e74705SXin Li bool ValidateCandidate(const TypoCorrection &candidate) override {
7667*67e74705SXin Li if (NamedDecl *ND = candidate.getCorrectionDecl())
7668*67e74705SXin Li return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7669*67e74705SXin Li return false;
7670*67e74705SXin Li }
7671*67e74705SXin Li };
7672*67e74705SXin Li
7673*67e74705SXin Li }
7674*67e74705SXin Li
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)7675*67e74705SXin Li static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7676*67e74705SXin Li CXXScopeSpec &SS,
7677*67e74705SXin Li SourceLocation IdentLoc,
7678*67e74705SXin Li IdentifierInfo *Ident) {
7679*67e74705SXin Li R.clear();
7680*67e74705SXin Li if (TypoCorrection Corrected =
7681*67e74705SXin Li S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7682*67e74705SXin Li llvm::make_unique<NamespaceValidatorCCC>(),
7683*67e74705SXin Li Sema::CTK_ErrorRecovery)) {
7684*67e74705SXin Li if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7685*67e74705SXin Li std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7686*67e74705SXin Li bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7687*67e74705SXin Li Ident->getName().equals(CorrectedStr);
7688*67e74705SXin Li S.diagnoseTypo(Corrected,
7689*67e74705SXin Li S.PDiag(diag::err_using_directive_member_suggest)
7690*67e74705SXin Li << Ident << DC << DroppedSpecifier << SS.getRange(),
7691*67e74705SXin Li S.PDiag(diag::note_namespace_defined_here));
7692*67e74705SXin Li } else {
7693*67e74705SXin Li S.diagnoseTypo(Corrected,
7694*67e74705SXin Li S.PDiag(diag::err_using_directive_suggest) << Ident,
7695*67e74705SXin Li S.PDiag(diag::note_namespace_defined_here));
7696*67e74705SXin Li }
7697*67e74705SXin Li R.addDecl(Corrected.getFoundDecl());
7698*67e74705SXin Li return true;
7699*67e74705SXin Li }
7700*67e74705SXin Li return false;
7701*67e74705SXin Li }
7702*67e74705SXin Li
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,AttributeList * AttrList)7703*67e74705SXin Li Decl *Sema::ActOnUsingDirective(Scope *S,
7704*67e74705SXin Li SourceLocation UsingLoc,
7705*67e74705SXin Li SourceLocation NamespcLoc,
7706*67e74705SXin Li CXXScopeSpec &SS,
7707*67e74705SXin Li SourceLocation IdentLoc,
7708*67e74705SXin Li IdentifierInfo *NamespcName,
7709*67e74705SXin Li AttributeList *AttrList) {
7710*67e74705SXin Li assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7711*67e74705SXin Li assert(NamespcName && "Invalid NamespcName.");
7712*67e74705SXin Li assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7713*67e74705SXin Li
7714*67e74705SXin Li // This can only happen along a recovery path.
7715*67e74705SXin Li while (S->isTemplateParamScope())
7716*67e74705SXin Li S = S->getParent();
7717*67e74705SXin Li assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7718*67e74705SXin Li
7719*67e74705SXin Li UsingDirectiveDecl *UDir = nullptr;
7720*67e74705SXin Li NestedNameSpecifier *Qualifier = nullptr;
7721*67e74705SXin Li if (SS.isSet())
7722*67e74705SXin Li Qualifier = SS.getScopeRep();
7723*67e74705SXin Li
7724*67e74705SXin Li // Lookup namespace name.
7725*67e74705SXin Li LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7726*67e74705SXin Li LookupParsedName(R, S, &SS);
7727*67e74705SXin Li if (R.isAmbiguous())
7728*67e74705SXin Li return nullptr;
7729*67e74705SXin Li
7730*67e74705SXin Li if (R.empty()) {
7731*67e74705SXin Li R.clear();
7732*67e74705SXin Li // Allow "using namespace std;" or "using namespace ::std;" even if
7733*67e74705SXin Li // "std" hasn't been defined yet, for GCC compatibility.
7734*67e74705SXin Li if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7735*67e74705SXin Li NamespcName->isStr("std")) {
7736*67e74705SXin Li Diag(IdentLoc, diag::ext_using_undefined_std);
7737*67e74705SXin Li R.addDecl(getOrCreateStdNamespace());
7738*67e74705SXin Li R.resolveKind();
7739*67e74705SXin Li }
7740*67e74705SXin Li // Otherwise, attempt typo correction.
7741*67e74705SXin Li else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7742*67e74705SXin Li }
7743*67e74705SXin Li
7744*67e74705SXin Li if (!R.empty()) {
7745*67e74705SXin Li NamedDecl *Named = R.getRepresentativeDecl();
7746*67e74705SXin Li NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
7747*67e74705SXin Li assert(NS && "expected namespace decl");
7748*67e74705SXin Li
7749*67e74705SXin Li // The use of a nested name specifier may trigger deprecation warnings.
7750*67e74705SXin Li DiagnoseUseOfDecl(Named, IdentLoc);
7751*67e74705SXin Li
7752*67e74705SXin Li // C++ [namespace.udir]p1:
7753*67e74705SXin Li // A using-directive specifies that the names in the nominated
7754*67e74705SXin Li // namespace can be used in the scope in which the
7755*67e74705SXin Li // using-directive appears after the using-directive. During
7756*67e74705SXin Li // unqualified name lookup (3.4.1), the names appear as if they
7757*67e74705SXin Li // were declared in the nearest enclosing namespace which
7758*67e74705SXin Li // contains both the using-directive and the nominated
7759*67e74705SXin Li // namespace. [Note: in this context, "contains" means "contains
7760*67e74705SXin Li // directly or indirectly". ]
7761*67e74705SXin Li
7762*67e74705SXin Li // Find enclosing context containing both using-directive and
7763*67e74705SXin Li // nominated namespace.
7764*67e74705SXin Li DeclContext *CommonAncestor = cast<DeclContext>(NS);
7765*67e74705SXin Li while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7766*67e74705SXin Li CommonAncestor = CommonAncestor->getParent();
7767*67e74705SXin Li
7768*67e74705SXin Li UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7769*67e74705SXin Li SS.getWithLocInContext(Context),
7770*67e74705SXin Li IdentLoc, Named, CommonAncestor);
7771*67e74705SXin Li
7772*67e74705SXin Li if (IsUsingDirectiveInToplevelContext(CurContext) &&
7773*67e74705SXin Li !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7774*67e74705SXin Li Diag(IdentLoc, diag::warn_using_directive_in_header);
7775*67e74705SXin Li }
7776*67e74705SXin Li
7777*67e74705SXin Li PushUsingDirective(S, UDir);
7778*67e74705SXin Li } else {
7779*67e74705SXin Li Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7780*67e74705SXin Li }
7781*67e74705SXin Li
7782*67e74705SXin Li if (UDir)
7783*67e74705SXin Li ProcessDeclAttributeList(S, UDir, AttrList);
7784*67e74705SXin Li
7785*67e74705SXin Li return UDir;
7786*67e74705SXin Li }
7787*67e74705SXin Li
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)7788*67e74705SXin Li void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7789*67e74705SXin Li // If the scope has an associated entity and the using directive is at
7790*67e74705SXin Li // namespace or translation unit scope, add the UsingDirectiveDecl into
7791*67e74705SXin Li // its lookup structure so qualified name lookup can find it.
7792*67e74705SXin Li DeclContext *Ctx = S->getEntity();
7793*67e74705SXin Li if (Ctx && !Ctx->isFunctionOrMethod())
7794*67e74705SXin Li Ctx->addDecl(UDir);
7795*67e74705SXin Li else
7796*67e74705SXin Li // Otherwise, it is at block scope. The using-directives will affect lookup
7797*67e74705SXin Li // only to the end of the scope.
7798*67e74705SXin Li S->PushUsingDirective(UDir);
7799*67e74705SXin Li }
7800*67e74705SXin Li
7801*67e74705SXin Li
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,bool HasUsingKeyword,SourceLocation UsingLoc,CXXScopeSpec & SS,UnqualifiedId & Name,AttributeList * AttrList,bool HasTypenameKeyword,SourceLocation TypenameLoc)7802*67e74705SXin Li Decl *Sema::ActOnUsingDeclaration(Scope *S,
7803*67e74705SXin Li AccessSpecifier AS,
7804*67e74705SXin Li bool HasUsingKeyword,
7805*67e74705SXin Li SourceLocation UsingLoc,
7806*67e74705SXin Li CXXScopeSpec &SS,
7807*67e74705SXin Li UnqualifiedId &Name,
7808*67e74705SXin Li AttributeList *AttrList,
7809*67e74705SXin Li bool HasTypenameKeyword,
7810*67e74705SXin Li SourceLocation TypenameLoc) {
7811*67e74705SXin Li assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7812*67e74705SXin Li
7813*67e74705SXin Li switch (Name.getKind()) {
7814*67e74705SXin Li case UnqualifiedId::IK_ImplicitSelfParam:
7815*67e74705SXin Li case UnqualifiedId::IK_Identifier:
7816*67e74705SXin Li case UnqualifiedId::IK_OperatorFunctionId:
7817*67e74705SXin Li case UnqualifiedId::IK_LiteralOperatorId:
7818*67e74705SXin Li case UnqualifiedId::IK_ConversionFunctionId:
7819*67e74705SXin Li break;
7820*67e74705SXin Li
7821*67e74705SXin Li case UnqualifiedId::IK_ConstructorName:
7822*67e74705SXin Li case UnqualifiedId::IK_ConstructorTemplateId:
7823*67e74705SXin Li // C++11 inheriting constructors.
7824*67e74705SXin Li Diag(Name.getLocStart(),
7825*67e74705SXin Li getLangOpts().CPlusPlus11 ?
7826*67e74705SXin Li diag::warn_cxx98_compat_using_decl_constructor :
7827*67e74705SXin Li diag::err_using_decl_constructor)
7828*67e74705SXin Li << SS.getRange();
7829*67e74705SXin Li
7830*67e74705SXin Li if (getLangOpts().CPlusPlus11) break;
7831*67e74705SXin Li
7832*67e74705SXin Li return nullptr;
7833*67e74705SXin Li
7834*67e74705SXin Li case UnqualifiedId::IK_DestructorName:
7835*67e74705SXin Li Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7836*67e74705SXin Li << SS.getRange();
7837*67e74705SXin Li return nullptr;
7838*67e74705SXin Li
7839*67e74705SXin Li case UnqualifiedId::IK_TemplateId:
7840*67e74705SXin Li Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7841*67e74705SXin Li << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7842*67e74705SXin Li return nullptr;
7843*67e74705SXin Li }
7844*67e74705SXin Li
7845*67e74705SXin Li DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7846*67e74705SXin Li DeclarationName TargetName = TargetNameInfo.getName();
7847*67e74705SXin Li if (!TargetName)
7848*67e74705SXin Li return nullptr;
7849*67e74705SXin Li
7850*67e74705SXin Li // Warn about access declarations.
7851*67e74705SXin Li if (!HasUsingKeyword) {
7852*67e74705SXin Li Diag(Name.getLocStart(),
7853*67e74705SXin Li getLangOpts().CPlusPlus11 ? diag::err_access_decl
7854*67e74705SXin Li : diag::warn_access_decl_deprecated)
7855*67e74705SXin Li << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7856*67e74705SXin Li }
7857*67e74705SXin Li
7858*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7859*67e74705SXin Li DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7860*67e74705SXin Li return nullptr;
7861*67e74705SXin Li
7862*67e74705SXin Li NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7863*67e74705SXin Li TargetNameInfo, AttrList,
7864*67e74705SXin Li /* IsInstantiation */ false,
7865*67e74705SXin Li HasTypenameKeyword, TypenameLoc);
7866*67e74705SXin Li if (UD)
7867*67e74705SXin Li PushOnScopeChains(UD, S, /*AddToContext*/ false);
7868*67e74705SXin Li
7869*67e74705SXin Li return UD;
7870*67e74705SXin Li }
7871*67e74705SXin Li
7872*67e74705SXin Li /// \brief Determine whether a using declaration considers the given
7873*67e74705SXin Li /// declarations as "equivalent", e.g., if they are redeclarations of
7874*67e74705SXin Li /// the same entity or are both typedefs of the same type.
7875*67e74705SXin Li static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2)7876*67e74705SXin Li IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7877*67e74705SXin Li if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7878*67e74705SXin Li return true;
7879*67e74705SXin Li
7880*67e74705SXin Li if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7881*67e74705SXin Li if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7882*67e74705SXin Li return Context.hasSameType(TD1->getUnderlyingType(),
7883*67e74705SXin Li TD2->getUnderlyingType());
7884*67e74705SXin Li
7885*67e74705SXin Li return false;
7886*67e74705SXin Li }
7887*67e74705SXin Li
7888*67e74705SXin Li
7889*67e74705SXin Li /// Determines whether to create a using shadow decl for a particular
7890*67e74705SXin Li /// decl, given the set of decls existing prior to this using lookup.
CheckUsingShadowDecl(UsingDecl * Using,NamedDecl * Orig,const LookupResult & Previous,UsingShadowDecl * & PrevShadow)7891*67e74705SXin Li bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7892*67e74705SXin Li const LookupResult &Previous,
7893*67e74705SXin Li UsingShadowDecl *&PrevShadow) {
7894*67e74705SXin Li // Diagnose finding a decl which is not from a base class of the
7895*67e74705SXin Li // current class. We do this now because there are cases where this
7896*67e74705SXin Li // function will silently decide not to build a shadow decl, which
7897*67e74705SXin Li // will pre-empt further diagnostics.
7898*67e74705SXin Li //
7899*67e74705SXin Li // We don't need to do this in C++11 because we do the check once on
7900*67e74705SXin Li // the qualifier.
7901*67e74705SXin Li //
7902*67e74705SXin Li // FIXME: diagnose the following if we care enough:
7903*67e74705SXin Li // struct A { int foo; };
7904*67e74705SXin Li // struct B : A { using A::foo; };
7905*67e74705SXin Li // template <class T> struct C : A {};
7906*67e74705SXin Li // template <class T> struct D : C<T> { using B::foo; } // <---
7907*67e74705SXin Li // This is invalid (during instantiation) in C++03 because B::foo
7908*67e74705SXin Li // resolves to the using decl in B, which is not a base class of D<T>.
7909*67e74705SXin Li // We can't diagnose it immediately because C<T> is an unknown
7910*67e74705SXin Li // specialization. The UsingShadowDecl in D<T> then points directly
7911*67e74705SXin Li // to A::foo, which will look well-formed when we instantiate.
7912*67e74705SXin Li // The right solution is to not collapse the shadow-decl chain.
7913*67e74705SXin Li if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7914*67e74705SXin Li DeclContext *OrigDC = Orig->getDeclContext();
7915*67e74705SXin Li
7916*67e74705SXin Li // Handle enums and anonymous structs.
7917*67e74705SXin Li if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7918*67e74705SXin Li CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7919*67e74705SXin Li while (OrigRec->isAnonymousStructOrUnion())
7920*67e74705SXin Li OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7921*67e74705SXin Li
7922*67e74705SXin Li if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7923*67e74705SXin Li if (OrigDC == CurContext) {
7924*67e74705SXin Li Diag(Using->getLocation(),
7925*67e74705SXin Li diag::err_using_decl_nested_name_specifier_is_current_class)
7926*67e74705SXin Li << Using->getQualifierLoc().getSourceRange();
7927*67e74705SXin Li Diag(Orig->getLocation(), diag::note_using_decl_target);
7928*67e74705SXin Li return true;
7929*67e74705SXin Li }
7930*67e74705SXin Li
7931*67e74705SXin Li Diag(Using->getQualifierLoc().getBeginLoc(),
7932*67e74705SXin Li diag::err_using_decl_nested_name_specifier_is_not_base_class)
7933*67e74705SXin Li << Using->getQualifier()
7934*67e74705SXin Li << cast<CXXRecordDecl>(CurContext)
7935*67e74705SXin Li << Using->getQualifierLoc().getSourceRange();
7936*67e74705SXin Li Diag(Orig->getLocation(), diag::note_using_decl_target);
7937*67e74705SXin Li return true;
7938*67e74705SXin Li }
7939*67e74705SXin Li }
7940*67e74705SXin Li
7941*67e74705SXin Li if (Previous.empty()) return false;
7942*67e74705SXin Li
7943*67e74705SXin Li NamedDecl *Target = Orig;
7944*67e74705SXin Li if (isa<UsingShadowDecl>(Target))
7945*67e74705SXin Li Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7946*67e74705SXin Li
7947*67e74705SXin Li // If the target happens to be one of the previous declarations, we
7948*67e74705SXin Li // don't have a conflict.
7949*67e74705SXin Li //
7950*67e74705SXin Li // FIXME: but we might be increasing its access, in which case we
7951*67e74705SXin Li // should redeclare it.
7952*67e74705SXin Li NamedDecl *NonTag = nullptr, *Tag = nullptr;
7953*67e74705SXin Li bool FoundEquivalentDecl = false;
7954*67e74705SXin Li for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7955*67e74705SXin Li I != E; ++I) {
7956*67e74705SXin Li NamedDecl *D = (*I)->getUnderlyingDecl();
7957*67e74705SXin Li // We can have UsingDecls in our Previous results because we use the same
7958*67e74705SXin Li // LookupResult for checking whether the UsingDecl itself is a valid
7959*67e74705SXin Li // redeclaration.
7960*67e74705SXin Li if (isa<UsingDecl>(D))
7961*67e74705SXin Li continue;
7962*67e74705SXin Li
7963*67e74705SXin Li if (IsEquivalentForUsingDecl(Context, D, Target)) {
7964*67e74705SXin Li if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7965*67e74705SXin Li PrevShadow = Shadow;
7966*67e74705SXin Li FoundEquivalentDecl = true;
7967*67e74705SXin Li } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
7968*67e74705SXin Li // We don't conflict with an existing using shadow decl of an equivalent
7969*67e74705SXin Li // declaration, but we're not a redeclaration of it.
7970*67e74705SXin Li FoundEquivalentDecl = true;
7971*67e74705SXin Li }
7972*67e74705SXin Li
7973*67e74705SXin Li if (isVisible(D))
7974*67e74705SXin Li (isa<TagDecl>(D) ? Tag : NonTag) = D;
7975*67e74705SXin Li }
7976*67e74705SXin Li
7977*67e74705SXin Li if (FoundEquivalentDecl)
7978*67e74705SXin Li return false;
7979*67e74705SXin Li
7980*67e74705SXin Li if (FunctionDecl *FD = Target->getAsFunction()) {
7981*67e74705SXin Li NamedDecl *OldDecl = nullptr;
7982*67e74705SXin Li switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7983*67e74705SXin Li /*IsForUsingDecl*/ true)) {
7984*67e74705SXin Li case Ovl_Overload:
7985*67e74705SXin Li return false;
7986*67e74705SXin Li
7987*67e74705SXin Li case Ovl_NonFunction:
7988*67e74705SXin Li Diag(Using->getLocation(), diag::err_using_decl_conflict);
7989*67e74705SXin Li break;
7990*67e74705SXin Li
7991*67e74705SXin Li // We found a decl with the exact signature.
7992*67e74705SXin Li case Ovl_Match:
7993*67e74705SXin Li // If we're in a record, we want to hide the target, so we
7994*67e74705SXin Li // return true (without a diagnostic) to tell the caller not to
7995*67e74705SXin Li // build a shadow decl.
7996*67e74705SXin Li if (CurContext->isRecord())
7997*67e74705SXin Li return true;
7998*67e74705SXin Li
7999*67e74705SXin Li // If we're not in a record, this is an error.
8000*67e74705SXin Li Diag(Using->getLocation(), diag::err_using_decl_conflict);
8001*67e74705SXin Li break;
8002*67e74705SXin Li }
8003*67e74705SXin Li
8004*67e74705SXin Li Diag(Target->getLocation(), diag::note_using_decl_target);
8005*67e74705SXin Li Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8006*67e74705SXin Li return true;
8007*67e74705SXin Li }
8008*67e74705SXin Li
8009*67e74705SXin Li // Target is not a function.
8010*67e74705SXin Li
8011*67e74705SXin Li if (isa<TagDecl>(Target)) {
8012*67e74705SXin Li // No conflict between a tag and a non-tag.
8013*67e74705SXin Li if (!Tag) return false;
8014*67e74705SXin Li
8015*67e74705SXin Li Diag(Using->getLocation(), diag::err_using_decl_conflict);
8016*67e74705SXin Li Diag(Target->getLocation(), diag::note_using_decl_target);
8017*67e74705SXin Li Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8018*67e74705SXin Li return true;
8019*67e74705SXin Li }
8020*67e74705SXin Li
8021*67e74705SXin Li // No conflict between a tag and a non-tag.
8022*67e74705SXin Li if (!NonTag) return false;
8023*67e74705SXin Li
8024*67e74705SXin Li Diag(Using->getLocation(), diag::err_using_decl_conflict);
8025*67e74705SXin Li Diag(Target->getLocation(), diag::note_using_decl_target);
8026*67e74705SXin Li Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8027*67e74705SXin Li return true;
8028*67e74705SXin Li }
8029*67e74705SXin Li
8030*67e74705SXin Li /// Determine whether a direct base class is a virtual base class.
isVirtualDirectBase(CXXRecordDecl * Derived,CXXRecordDecl * Base)8031*67e74705SXin Li static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8032*67e74705SXin Li if (!Derived->getNumVBases())
8033*67e74705SXin Li return false;
8034*67e74705SXin Li for (auto &B : Derived->bases())
8035*67e74705SXin Li if (B.getType()->getAsCXXRecordDecl() == Base)
8036*67e74705SXin Li return B.isVirtual();
8037*67e74705SXin Li llvm_unreachable("not a direct base class");
8038*67e74705SXin Li }
8039*67e74705SXin Li
8040*67e74705SXin Li /// Builds a shadow declaration corresponding to a 'using' declaration.
BuildUsingShadowDecl(Scope * S,UsingDecl * UD,NamedDecl * Orig,UsingShadowDecl * PrevDecl)8041*67e74705SXin Li UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
8042*67e74705SXin Li UsingDecl *UD,
8043*67e74705SXin Li NamedDecl *Orig,
8044*67e74705SXin Li UsingShadowDecl *PrevDecl) {
8045*67e74705SXin Li // If we resolved to another shadow declaration, just coalesce them.
8046*67e74705SXin Li NamedDecl *Target = Orig;
8047*67e74705SXin Li if (isa<UsingShadowDecl>(Target)) {
8048*67e74705SXin Li Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8049*67e74705SXin Li assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
8050*67e74705SXin Li }
8051*67e74705SXin Li
8052*67e74705SXin Li NamedDecl *NonTemplateTarget = Target;
8053*67e74705SXin Li if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8054*67e74705SXin Li NonTemplateTarget = TargetTD->getTemplatedDecl();
8055*67e74705SXin Li
8056*67e74705SXin Li UsingShadowDecl *Shadow;
8057*67e74705SXin Li if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8058*67e74705SXin Li bool IsVirtualBase =
8059*67e74705SXin Li isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8060*67e74705SXin Li UD->getQualifier()->getAsRecordDecl());
8061*67e74705SXin Li Shadow = ConstructorUsingShadowDecl::Create(
8062*67e74705SXin Li Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8063*67e74705SXin Li } else {
8064*67e74705SXin Li Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8065*67e74705SXin Li Target);
8066*67e74705SXin Li }
8067*67e74705SXin Li UD->addShadowDecl(Shadow);
8068*67e74705SXin Li
8069*67e74705SXin Li Shadow->setAccess(UD->getAccess());
8070*67e74705SXin Li if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8071*67e74705SXin Li Shadow->setInvalidDecl();
8072*67e74705SXin Li
8073*67e74705SXin Li Shadow->setPreviousDecl(PrevDecl);
8074*67e74705SXin Li
8075*67e74705SXin Li if (S)
8076*67e74705SXin Li PushOnScopeChains(Shadow, S);
8077*67e74705SXin Li else
8078*67e74705SXin Li CurContext->addDecl(Shadow);
8079*67e74705SXin Li
8080*67e74705SXin Li
8081*67e74705SXin Li return Shadow;
8082*67e74705SXin Li }
8083*67e74705SXin Li
8084*67e74705SXin Li /// Hides a using shadow declaration. This is required by the current
8085*67e74705SXin Li /// using-decl implementation when a resolvable using declaration in a
8086*67e74705SXin Li /// class is followed by a declaration which would hide or override
8087*67e74705SXin Li /// one or more of the using decl's targets; for example:
8088*67e74705SXin Li ///
8089*67e74705SXin Li /// struct Base { void foo(int); };
8090*67e74705SXin Li /// struct Derived : Base {
8091*67e74705SXin Li /// using Base::foo;
8092*67e74705SXin Li /// void foo(int);
8093*67e74705SXin Li /// };
8094*67e74705SXin Li ///
8095*67e74705SXin Li /// The governing language is C++03 [namespace.udecl]p12:
8096*67e74705SXin Li ///
8097*67e74705SXin Li /// When a using-declaration brings names from a base class into a
8098*67e74705SXin Li /// derived class scope, member functions in the derived class
8099*67e74705SXin Li /// override and/or hide member functions with the same name and
8100*67e74705SXin Li /// parameter types in a base class (rather than conflicting).
8101*67e74705SXin Li ///
8102*67e74705SXin Li /// There are two ways to implement this:
8103*67e74705SXin Li /// (1) optimistically create shadow decls when they're not hidden
8104*67e74705SXin Li /// by existing declarations, or
8105*67e74705SXin Li /// (2) don't create any shadow decls (or at least don't make them
8106*67e74705SXin Li /// visible) until we've fully parsed/instantiated the class.
8107*67e74705SXin Li /// The problem with (1) is that we might have to retroactively remove
8108*67e74705SXin Li /// a shadow decl, which requires several O(n) operations because the
8109*67e74705SXin Li /// decl structures are (very reasonably) not designed for removal.
8110*67e74705SXin Li /// (2) avoids this but is very fiddly and phase-dependent.
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)8111*67e74705SXin Li void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
8112*67e74705SXin Li if (Shadow->getDeclName().getNameKind() ==
8113*67e74705SXin Li DeclarationName::CXXConversionFunctionName)
8114*67e74705SXin Li cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8115*67e74705SXin Li
8116*67e74705SXin Li // Remove it from the DeclContext...
8117*67e74705SXin Li Shadow->getDeclContext()->removeDecl(Shadow);
8118*67e74705SXin Li
8119*67e74705SXin Li // ...and the scope, if applicable...
8120*67e74705SXin Li if (S) {
8121*67e74705SXin Li S->RemoveDecl(Shadow);
8122*67e74705SXin Li IdResolver.RemoveDecl(Shadow);
8123*67e74705SXin Li }
8124*67e74705SXin Li
8125*67e74705SXin Li // ...and the using decl.
8126*67e74705SXin Li Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8127*67e74705SXin Li
8128*67e74705SXin Li // TODO: complain somehow if Shadow was used. It shouldn't
8129*67e74705SXin Li // be possible for this to happen, because...?
8130*67e74705SXin Li }
8131*67e74705SXin Li
8132*67e74705SXin Li /// Find the base specifier for a base class with the given type.
findDirectBaseWithType(CXXRecordDecl * Derived,QualType DesiredBase,bool & AnyDependentBases)8133*67e74705SXin Li static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8134*67e74705SXin Li QualType DesiredBase,
8135*67e74705SXin Li bool &AnyDependentBases) {
8136*67e74705SXin Li // Check whether the named type is a direct base class.
8137*67e74705SXin Li CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8138*67e74705SXin Li for (auto &Base : Derived->bases()) {
8139*67e74705SXin Li CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8140*67e74705SXin Li if (CanonicalDesiredBase == BaseType)
8141*67e74705SXin Li return &Base;
8142*67e74705SXin Li if (BaseType->isDependentType())
8143*67e74705SXin Li AnyDependentBases = true;
8144*67e74705SXin Li }
8145*67e74705SXin Li return nullptr;
8146*67e74705SXin Li }
8147*67e74705SXin Li
8148*67e74705SXin Li namespace {
8149*67e74705SXin Li class UsingValidatorCCC : public CorrectionCandidateCallback {
8150*67e74705SXin Li public:
UsingValidatorCCC(bool HasTypenameKeyword,bool IsInstantiation,NestedNameSpecifier * NNS,CXXRecordDecl * RequireMemberOf)8151*67e74705SXin Li UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
8152*67e74705SXin Li NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
8153*67e74705SXin Li : HasTypenameKeyword(HasTypenameKeyword),
8154*67e74705SXin Li IsInstantiation(IsInstantiation), OldNNS(NNS),
8155*67e74705SXin Li RequireMemberOf(RequireMemberOf) {}
8156*67e74705SXin Li
ValidateCandidate(const TypoCorrection & Candidate)8157*67e74705SXin Li bool ValidateCandidate(const TypoCorrection &Candidate) override {
8158*67e74705SXin Li NamedDecl *ND = Candidate.getCorrectionDecl();
8159*67e74705SXin Li
8160*67e74705SXin Li // Keywords are not valid here.
8161*67e74705SXin Li if (!ND || isa<NamespaceDecl>(ND))
8162*67e74705SXin Li return false;
8163*67e74705SXin Li
8164*67e74705SXin Li // Completely unqualified names are invalid for a 'using' declaration.
8165*67e74705SXin Li if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8166*67e74705SXin Li return false;
8167*67e74705SXin Li
8168*67e74705SXin Li // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8169*67e74705SXin Li // reject.
8170*67e74705SXin Li
8171*67e74705SXin Li if (RequireMemberOf) {
8172*67e74705SXin Li auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8173*67e74705SXin Li if (FoundRecord && FoundRecord->isInjectedClassName()) {
8174*67e74705SXin Li // No-one ever wants a using-declaration to name an injected-class-name
8175*67e74705SXin Li // of a base class, unless they're declaring an inheriting constructor.
8176*67e74705SXin Li ASTContext &Ctx = ND->getASTContext();
8177*67e74705SXin Li if (!Ctx.getLangOpts().CPlusPlus11)
8178*67e74705SXin Li return false;
8179*67e74705SXin Li QualType FoundType = Ctx.getRecordType(FoundRecord);
8180*67e74705SXin Li
8181*67e74705SXin Li // Check that the injected-class-name is named as a member of its own
8182*67e74705SXin Li // type; we don't want to suggest 'using Derived::Base;', since that
8183*67e74705SXin Li // means something else.
8184*67e74705SXin Li NestedNameSpecifier *Specifier =
8185*67e74705SXin Li Candidate.WillReplaceSpecifier()
8186*67e74705SXin Li ? Candidate.getCorrectionSpecifier()
8187*67e74705SXin Li : OldNNS;
8188*67e74705SXin Li if (!Specifier->getAsType() ||
8189*67e74705SXin Li !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8190*67e74705SXin Li return false;
8191*67e74705SXin Li
8192*67e74705SXin Li // Check that this inheriting constructor declaration actually names a
8193*67e74705SXin Li // direct base class of the current class.
8194*67e74705SXin Li bool AnyDependentBases = false;
8195*67e74705SXin Li if (!findDirectBaseWithType(RequireMemberOf,
8196*67e74705SXin Li Ctx.getRecordType(FoundRecord),
8197*67e74705SXin Li AnyDependentBases) &&
8198*67e74705SXin Li !AnyDependentBases)
8199*67e74705SXin Li return false;
8200*67e74705SXin Li } else {
8201*67e74705SXin Li auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8202*67e74705SXin Li if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8203*67e74705SXin Li return false;
8204*67e74705SXin Li
8205*67e74705SXin Li // FIXME: Check that the base class member is accessible?
8206*67e74705SXin Li }
8207*67e74705SXin Li } else {
8208*67e74705SXin Li auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8209*67e74705SXin Li if (FoundRecord && FoundRecord->isInjectedClassName())
8210*67e74705SXin Li return false;
8211*67e74705SXin Li }
8212*67e74705SXin Li
8213*67e74705SXin Li if (isa<TypeDecl>(ND))
8214*67e74705SXin Li return HasTypenameKeyword || !IsInstantiation;
8215*67e74705SXin Li
8216*67e74705SXin Li return !HasTypenameKeyword;
8217*67e74705SXin Li }
8218*67e74705SXin Li
8219*67e74705SXin Li private:
8220*67e74705SXin Li bool HasTypenameKeyword;
8221*67e74705SXin Li bool IsInstantiation;
8222*67e74705SXin Li NestedNameSpecifier *OldNNS;
8223*67e74705SXin Li CXXRecordDecl *RequireMemberOf;
8224*67e74705SXin Li };
8225*67e74705SXin Li } // end anonymous namespace
8226*67e74705SXin Li
8227*67e74705SXin Li /// Builds a using declaration.
8228*67e74705SXin Li ///
8229*67e74705SXin Li /// \param IsInstantiation - Whether this call arises from an
8230*67e74705SXin Li /// instantiation of an unresolved using declaration. We treat
8231*67e74705SXin Li /// the lookup differently for these declarations.
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,CXXScopeSpec & SS,DeclarationNameInfo NameInfo,AttributeList * AttrList,bool IsInstantiation,bool HasTypenameKeyword,SourceLocation TypenameLoc)8232*67e74705SXin Li NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8233*67e74705SXin Li SourceLocation UsingLoc,
8234*67e74705SXin Li CXXScopeSpec &SS,
8235*67e74705SXin Li DeclarationNameInfo NameInfo,
8236*67e74705SXin Li AttributeList *AttrList,
8237*67e74705SXin Li bool IsInstantiation,
8238*67e74705SXin Li bool HasTypenameKeyword,
8239*67e74705SXin Li SourceLocation TypenameLoc) {
8240*67e74705SXin Li assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8241*67e74705SXin Li SourceLocation IdentLoc = NameInfo.getLoc();
8242*67e74705SXin Li assert(IdentLoc.isValid() && "Invalid TargetName location.");
8243*67e74705SXin Li
8244*67e74705SXin Li // FIXME: We ignore attributes for now.
8245*67e74705SXin Li
8246*67e74705SXin Li if (SS.isEmpty()) {
8247*67e74705SXin Li Diag(IdentLoc, diag::err_using_requires_qualname);
8248*67e74705SXin Li return nullptr;
8249*67e74705SXin Li }
8250*67e74705SXin Li
8251*67e74705SXin Li // For an inheriting constructor declaration, the name of the using
8252*67e74705SXin Li // declaration is the name of a constructor in this class, not in the
8253*67e74705SXin Li // base class.
8254*67e74705SXin Li DeclarationNameInfo UsingName = NameInfo;
8255*67e74705SXin Li if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
8256*67e74705SXin Li if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
8257*67e74705SXin Li UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
8258*67e74705SXin Li Context.getCanonicalType(Context.getRecordType(RD))));
8259*67e74705SXin Li
8260*67e74705SXin Li // Do the redeclaration lookup in the current scope.
8261*67e74705SXin Li LookupResult Previous(*this, UsingName, LookupUsingDeclName,
8262*67e74705SXin Li ForRedeclaration);
8263*67e74705SXin Li Previous.setHideTags(false);
8264*67e74705SXin Li if (S) {
8265*67e74705SXin Li LookupName(Previous, S);
8266*67e74705SXin Li
8267*67e74705SXin Li // It is really dumb that we have to do this.
8268*67e74705SXin Li LookupResult::Filter F = Previous.makeFilter();
8269*67e74705SXin Li while (F.hasNext()) {
8270*67e74705SXin Li NamedDecl *D = F.next();
8271*67e74705SXin Li if (!isDeclInScope(D, CurContext, S))
8272*67e74705SXin Li F.erase();
8273*67e74705SXin Li // If we found a local extern declaration that's not ordinarily visible,
8274*67e74705SXin Li // and this declaration is being added to a non-block scope, ignore it.
8275*67e74705SXin Li // We're only checking for scope conflicts here, not also for violations
8276*67e74705SXin Li // of the linkage rules.
8277*67e74705SXin Li else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8278*67e74705SXin Li !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8279*67e74705SXin Li F.erase();
8280*67e74705SXin Li }
8281*67e74705SXin Li F.done();
8282*67e74705SXin Li } else {
8283*67e74705SXin Li assert(IsInstantiation && "no scope in non-instantiation");
8284*67e74705SXin Li assert(CurContext->isRecord() && "scope not record in instantiation");
8285*67e74705SXin Li LookupQualifiedName(Previous, CurContext);
8286*67e74705SXin Li }
8287*67e74705SXin Li
8288*67e74705SXin Li // Check for invalid redeclarations.
8289*67e74705SXin Li if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8290*67e74705SXin Li SS, IdentLoc, Previous))
8291*67e74705SXin Li return nullptr;
8292*67e74705SXin Li
8293*67e74705SXin Li // Check for bad qualifiers.
8294*67e74705SXin Li if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8295*67e74705SXin Li return nullptr;
8296*67e74705SXin Li
8297*67e74705SXin Li DeclContext *LookupContext = computeDeclContext(SS);
8298*67e74705SXin Li NamedDecl *D;
8299*67e74705SXin Li NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8300*67e74705SXin Li if (!LookupContext) {
8301*67e74705SXin Li if (HasTypenameKeyword) {
8302*67e74705SXin Li // FIXME: not all declaration name kinds are legal here
8303*67e74705SXin Li D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8304*67e74705SXin Li UsingLoc, TypenameLoc,
8305*67e74705SXin Li QualifierLoc,
8306*67e74705SXin Li IdentLoc, NameInfo.getName());
8307*67e74705SXin Li } else {
8308*67e74705SXin Li D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8309*67e74705SXin Li QualifierLoc, NameInfo);
8310*67e74705SXin Li }
8311*67e74705SXin Li D->setAccess(AS);
8312*67e74705SXin Li CurContext->addDecl(D);
8313*67e74705SXin Li return D;
8314*67e74705SXin Li }
8315*67e74705SXin Li
8316*67e74705SXin Li auto Build = [&](bool Invalid) {
8317*67e74705SXin Li UsingDecl *UD =
8318*67e74705SXin Li UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
8319*67e74705SXin Li UsingName, HasTypenameKeyword);
8320*67e74705SXin Li UD->setAccess(AS);
8321*67e74705SXin Li CurContext->addDecl(UD);
8322*67e74705SXin Li UD->setInvalidDecl(Invalid);
8323*67e74705SXin Li return UD;
8324*67e74705SXin Li };
8325*67e74705SXin Li auto BuildInvalid = [&]{ return Build(true); };
8326*67e74705SXin Li auto BuildValid = [&]{ return Build(false); };
8327*67e74705SXin Li
8328*67e74705SXin Li if (RequireCompleteDeclContext(SS, LookupContext))
8329*67e74705SXin Li return BuildInvalid();
8330*67e74705SXin Li
8331*67e74705SXin Li // Look up the target name.
8332*67e74705SXin Li LookupResult R(*this, NameInfo, LookupOrdinaryName);
8333*67e74705SXin Li
8334*67e74705SXin Li // Unlike most lookups, we don't always want to hide tag
8335*67e74705SXin Li // declarations: tag names are visible through the using declaration
8336*67e74705SXin Li // even if hidden by ordinary names, *except* in a dependent context
8337*67e74705SXin Li // where it's important for the sanity of two-phase lookup.
8338*67e74705SXin Li if (!IsInstantiation)
8339*67e74705SXin Li R.setHideTags(false);
8340*67e74705SXin Li
8341*67e74705SXin Li // For the purposes of this lookup, we have a base object type
8342*67e74705SXin Li // equal to that of the current context.
8343*67e74705SXin Li if (CurContext->isRecord()) {
8344*67e74705SXin Li R.setBaseObjectType(
8345*67e74705SXin Li Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8346*67e74705SXin Li }
8347*67e74705SXin Li
8348*67e74705SXin Li LookupQualifiedName(R, LookupContext);
8349*67e74705SXin Li
8350*67e74705SXin Li // Try to correct typos if possible. If constructor name lookup finds no
8351*67e74705SXin Li // results, that means the named class has no explicit constructors, and we
8352*67e74705SXin Li // suppressed declaring implicit ones (probably because it's dependent or
8353*67e74705SXin Li // invalid).
8354*67e74705SXin Li if (R.empty() &&
8355*67e74705SXin Li NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8356*67e74705SXin Li if (TypoCorrection Corrected = CorrectTypo(
8357*67e74705SXin Li R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8358*67e74705SXin Li llvm::make_unique<UsingValidatorCCC>(
8359*67e74705SXin Li HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8360*67e74705SXin Li dyn_cast<CXXRecordDecl>(CurContext)),
8361*67e74705SXin Li CTK_ErrorRecovery)) {
8362*67e74705SXin Li // We reject any correction for which ND would be NULL.
8363*67e74705SXin Li NamedDecl *ND = Corrected.getCorrectionDecl();
8364*67e74705SXin Li
8365*67e74705SXin Li // We reject candidates where DroppedSpecifier == true, hence the
8366*67e74705SXin Li // literal '0' below.
8367*67e74705SXin Li diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8368*67e74705SXin Li << NameInfo.getName() << LookupContext << 0
8369*67e74705SXin Li << SS.getRange());
8370*67e74705SXin Li
8371*67e74705SXin Li // If we corrected to an inheriting constructor, handle it as one.
8372*67e74705SXin Li auto *RD = dyn_cast<CXXRecordDecl>(ND);
8373*67e74705SXin Li if (RD && RD->isInjectedClassName()) {
8374*67e74705SXin Li // The parent of the injected class name is the class itself.
8375*67e74705SXin Li RD = cast<CXXRecordDecl>(RD->getParent());
8376*67e74705SXin Li
8377*67e74705SXin Li // Fix up the information we'll use to build the using declaration.
8378*67e74705SXin Li if (Corrected.WillReplaceSpecifier()) {
8379*67e74705SXin Li NestedNameSpecifierLocBuilder Builder;
8380*67e74705SXin Li Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8381*67e74705SXin Li QualifierLoc.getSourceRange());
8382*67e74705SXin Li QualifierLoc = Builder.getWithLocInContext(Context);
8383*67e74705SXin Li }
8384*67e74705SXin Li
8385*67e74705SXin Li // In this case, the name we introduce is the name of a derived class
8386*67e74705SXin Li // constructor.
8387*67e74705SXin Li auto *CurClass = cast<CXXRecordDecl>(CurContext);
8388*67e74705SXin Li UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
8389*67e74705SXin Li Context.getCanonicalType(Context.getRecordType(CurClass))));
8390*67e74705SXin Li UsingName.setNamedTypeInfo(nullptr);
8391*67e74705SXin Li for (auto *Ctor : LookupConstructors(RD))
8392*67e74705SXin Li R.addDecl(Ctor);
8393*67e74705SXin Li R.resolveKind();
8394*67e74705SXin Li } else {
8395*67e74705SXin Li // FIXME: Pick up all the declarations if we found an overloaded
8396*67e74705SXin Li // function.
8397*67e74705SXin Li UsingName.setName(ND->getDeclName());
8398*67e74705SXin Li R.addDecl(ND);
8399*67e74705SXin Li }
8400*67e74705SXin Li } else {
8401*67e74705SXin Li Diag(IdentLoc, diag::err_no_member)
8402*67e74705SXin Li << NameInfo.getName() << LookupContext << SS.getRange();
8403*67e74705SXin Li return BuildInvalid();
8404*67e74705SXin Li }
8405*67e74705SXin Li }
8406*67e74705SXin Li
8407*67e74705SXin Li if (R.isAmbiguous())
8408*67e74705SXin Li return BuildInvalid();
8409*67e74705SXin Li
8410*67e74705SXin Li if (HasTypenameKeyword) {
8411*67e74705SXin Li // If we asked for a typename and got a non-type decl, error out.
8412*67e74705SXin Li if (!R.getAsSingle<TypeDecl>()) {
8413*67e74705SXin Li Diag(IdentLoc, diag::err_using_typename_non_type);
8414*67e74705SXin Li for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8415*67e74705SXin Li Diag((*I)->getUnderlyingDecl()->getLocation(),
8416*67e74705SXin Li diag::note_using_decl_target);
8417*67e74705SXin Li return BuildInvalid();
8418*67e74705SXin Li }
8419*67e74705SXin Li } else {
8420*67e74705SXin Li // If we asked for a non-typename and we got a type, error out,
8421*67e74705SXin Li // but only if this is an instantiation of an unresolved using
8422*67e74705SXin Li // decl. Otherwise just silently find the type name.
8423*67e74705SXin Li if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8424*67e74705SXin Li Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8425*67e74705SXin Li Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8426*67e74705SXin Li return BuildInvalid();
8427*67e74705SXin Li }
8428*67e74705SXin Li }
8429*67e74705SXin Li
8430*67e74705SXin Li // C++14 [namespace.udecl]p6:
8431*67e74705SXin Li // A using-declaration shall not name a namespace.
8432*67e74705SXin Li if (R.getAsSingle<NamespaceDecl>()) {
8433*67e74705SXin Li Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8434*67e74705SXin Li << SS.getRange();
8435*67e74705SXin Li return BuildInvalid();
8436*67e74705SXin Li }
8437*67e74705SXin Li
8438*67e74705SXin Li // C++14 [namespace.udecl]p7:
8439*67e74705SXin Li // A using-declaration shall not name a scoped enumerator.
8440*67e74705SXin Li if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
8441*67e74705SXin Li if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
8442*67e74705SXin Li Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
8443*67e74705SXin Li << SS.getRange();
8444*67e74705SXin Li return BuildInvalid();
8445*67e74705SXin Li }
8446*67e74705SXin Li }
8447*67e74705SXin Li
8448*67e74705SXin Li UsingDecl *UD = BuildValid();
8449*67e74705SXin Li
8450*67e74705SXin Li // Some additional rules apply to inheriting constructors.
8451*67e74705SXin Li if (UsingName.getName().getNameKind() ==
8452*67e74705SXin Li DeclarationName::CXXConstructorName) {
8453*67e74705SXin Li // Suppress access diagnostics; the access check is instead performed at the
8454*67e74705SXin Li // point of use for an inheriting constructor.
8455*67e74705SXin Li R.suppressDiagnostics();
8456*67e74705SXin Li if (CheckInheritingConstructorUsingDecl(UD))
8457*67e74705SXin Li return UD;
8458*67e74705SXin Li }
8459*67e74705SXin Li
8460*67e74705SXin Li for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8461*67e74705SXin Li UsingShadowDecl *PrevDecl = nullptr;
8462*67e74705SXin Li if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8463*67e74705SXin Li BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8464*67e74705SXin Li }
8465*67e74705SXin Li
8466*67e74705SXin Li return UD;
8467*67e74705SXin Li }
8468*67e74705SXin Li
8469*67e74705SXin Li /// Additional checks for a using declaration referring to a constructor name.
CheckInheritingConstructorUsingDecl(UsingDecl * UD)8470*67e74705SXin Li bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8471*67e74705SXin Li assert(!UD->hasTypename() && "expecting a constructor name");
8472*67e74705SXin Li
8473*67e74705SXin Li const Type *SourceType = UD->getQualifier()->getAsType();
8474*67e74705SXin Li assert(SourceType &&
8475*67e74705SXin Li "Using decl naming constructor doesn't have type in scope spec.");
8476*67e74705SXin Li CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8477*67e74705SXin Li
8478*67e74705SXin Li // Check whether the named type is a direct base class.
8479*67e74705SXin Li bool AnyDependentBases = false;
8480*67e74705SXin Li auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8481*67e74705SXin Li AnyDependentBases);
8482*67e74705SXin Li if (!Base && !AnyDependentBases) {
8483*67e74705SXin Li Diag(UD->getUsingLoc(),
8484*67e74705SXin Li diag::err_using_decl_constructor_not_in_direct_base)
8485*67e74705SXin Li << UD->getNameInfo().getSourceRange()
8486*67e74705SXin Li << QualType(SourceType, 0) << TargetClass;
8487*67e74705SXin Li UD->setInvalidDecl();
8488*67e74705SXin Li return true;
8489*67e74705SXin Li }
8490*67e74705SXin Li
8491*67e74705SXin Li if (Base)
8492*67e74705SXin Li Base->setInheritConstructors();
8493*67e74705SXin Li
8494*67e74705SXin Li return false;
8495*67e74705SXin Li }
8496*67e74705SXin Li
8497*67e74705SXin Li /// Checks that the given using declaration is not an invalid
8498*67e74705SXin Li /// redeclaration. Note that this is checking only for the using decl
8499*67e74705SXin Li /// itself, not for any ill-formedness among the UsingShadowDecls.
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool HasTypenameKeyword,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)8500*67e74705SXin Li bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8501*67e74705SXin Li bool HasTypenameKeyword,
8502*67e74705SXin Li const CXXScopeSpec &SS,
8503*67e74705SXin Li SourceLocation NameLoc,
8504*67e74705SXin Li const LookupResult &Prev) {
8505*67e74705SXin Li // C++03 [namespace.udecl]p8:
8506*67e74705SXin Li // C++0x [namespace.udecl]p10:
8507*67e74705SXin Li // A using-declaration is a declaration and can therefore be used
8508*67e74705SXin Li // repeatedly where (and only where) multiple declarations are
8509*67e74705SXin Li // allowed.
8510*67e74705SXin Li //
8511*67e74705SXin Li // That's in non-member contexts.
8512*67e74705SXin Li if (!CurContext->getRedeclContext()->isRecord())
8513*67e74705SXin Li return false;
8514*67e74705SXin Li
8515*67e74705SXin Li NestedNameSpecifier *Qual = SS.getScopeRep();
8516*67e74705SXin Li
8517*67e74705SXin Li for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8518*67e74705SXin Li NamedDecl *D = *I;
8519*67e74705SXin Li
8520*67e74705SXin Li bool DTypename;
8521*67e74705SXin Li NestedNameSpecifier *DQual;
8522*67e74705SXin Li if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8523*67e74705SXin Li DTypename = UD->hasTypename();
8524*67e74705SXin Li DQual = UD->getQualifier();
8525*67e74705SXin Li } else if (UnresolvedUsingValueDecl *UD
8526*67e74705SXin Li = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8527*67e74705SXin Li DTypename = false;
8528*67e74705SXin Li DQual = UD->getQualifier();
8529*67e74705SXin Li } else if (UnresolvedUsingTypenameDecl *UD
8530*67e74705SXin Li = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8531*67e74705SXin Li DTypename = true;
8532*67e74705SXin Li DQual = UD->getQualifier();
8533*67e74705SXin Li } else continue;
8534*67e74705SXin Li
8535*67e74705SXin Li // using decls differ if one says 'typename' and the other doesn't.
8536*67e74705SXin Li // FIXME: non-dependent using decls?
8537*67e74705SXin Li if (HasTypenameKeyword != DTypename) continue;
8538*67e74705SXin Li
8539*67e74705SXin Li // using decls differ if they name different scopes (but note that
8540*67e74705SXin Li // template instantiation can cause this check to trigger when it
8541*67e74705SXin Li // didn't before instantiation).
8542*67e74705SXin Li if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8543*67e74705SXin Li Context.getCanonicalNestedNameSpecifier(DQual))
8544*67e74705SXin Li continue;
8545*67e74705SXin Li
8546*67e74705SXin Li Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8547*67e74705SXin Li Diag(D->getLocation(), diag::note_using_decl) << 1;
8548*67e74705SXin Li return true;
8549*67e74705SXin Li }
8550*67e74705SXin Li
8551*67e74705SXin Li return false;
8552*67e74705SXin Li }
8553*67e74705SXin Li
8554*67e74705SXin Li
8555*67e74705SXin Li /// Checks that the given nested-name qualifier used in a using decl
8556*67e74705SXin Li /// in the current context is appropriately related to the current
8557*67e74705SXin Li /// scope. If an error is found, diagnoses it and returns true.
CheckUsingDeclQualifier(SourceLocation UsingLoc,const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,SourceLocation NameLoc)8558*67e74705SXin Li bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8559*67e74705SXin Li const CXXScopeSpec &SS,
8560*67e74705SXin Li const DeclarationNameInfo &NameInfo,
8561*67e74705SXin Li SourceLocation NameLoc) {
8562*67e74705SXin Li DeclContext *NamedContext = computeDeclContext(SS);
8563*67e74705SXin Li
8564*67e74705SXin Li if (!CurContext->isRecord()) {
8565*67e74705SXin Li // C++03 [namespace.udecl]p3:
8566*67e74705SXin Li // C++0x [namespace.udecl]p8:
8567*67e74705SXin Li // A using-declaration for a class member shall be a member-declaration.
8568*67e74705SXin Li
8569*67e74705SXin Li // If we weren't able to compute a valid scope, it must be a
8570*67e74705SXin Li // dependent class scope.
8571*67e74705SXin Li if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
8572*67e74705SXin Li auto *RD = NamedContext
8573*67e74705SXin Li ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
8574*67e74705SXin Li : nullptr;
8575*67e74705SXin Li if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8576*67e74705SXin Li RD = nullptr;
8577*67e74705SXin Li
8578*67e74705SXin Li Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8579*67e74705SXin Li << SS.getRange();
8580*67e74705SXin Li
8581*67e74705SXin Li // If we have a complete, non-dependent source type, try to suggest a
8582*67e74705SXin Li // way to get the same effect.
8583*67e74705SXin Li if (!RD)
8584*67e74705SXin Li return true;
8585*67e74705SXin Li
8586*67e74705SXin Li // Find what this using-declaration was referring to.
8587*67e74705SXin Li LookupResult R(*this, NameInfo, LookupOrdinaryName);
8588*67e74705SXin Li R.setHideTags(false);
8589*67e74705SXin Li R.suppressDiagnostics();
8590*67e74705SXin Li LookupQualifiedName(R, RD);
8591*67e74705SXin Li
8592*67e74705SXin Li if (R.getAsSingle<TypeDecl>()) {
8593*67e74705SXin Li if (getLangOpts().CPlusPlus11) {
8594*67e74705SXin Li // Convert 'using X::Y;' to 'using Y = X::Y;'.
8595*67e74705SXin Li Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8596*67e74705SXin Li << 0 // alias declaration
8597*67e74705SXin Li << FixItHint::CreateInsertion(SS.getBeginLoc(),
8598*67e74705SXin Li NameInfo.getName().getAsString() +
8599*67e74705SXin Li " = ");
8600*67e74705SXin Li } else {
8601*67e74705SXin Li // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8602*67e74705SXin Li SourceLocation InsertLoc =
8603*67e74705SXin Li getLocForEndOfToken(NameInfo.getLocEnd());
8604*67e74705SXin Li Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8605*67e74705SXin Li << 1 // typedef declaration
8606*67e74705SXin Li << FixItHint::CreateReplacement(UsingLoc, "typedef")
8607*67e74705SXin Li << FixItHint::CreateInsertion(
8608*67e74705SXin Li InsertLoc, " " + NameInfo.getName().getAsString());
8609*67e74705SXin Li }
8610*67e74705SXin Li } else if (R.getAsSingle<VarDecl>()) {
8611*67e74705SXin Li // Don't provide a fixit outside C++11 mode; we don't want to suggest
8612*67e74705SXin Li // repeating the type of the static data member here.
8613*67e74705SXin Li FixItHint FixIt;
8614*67e74705SXin Li if (getLangOpts().CPlusPlus11) {
8615*67e74705SXin Li // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8616*67e74705SXin Li FixIt = FixItHint::CreateReplacement(
8617*67e74705SXin Li UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8618*67e74705SXin Li }
8619*67e74705SXin Li
8620*67e74705SXin Li Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8621*67e74705SXin Li << 2 // reference declaration
8622*67e74705SXin Li << FixIt;
8623*67e74705SXin Li } else if (R.getAsSingle<EnumConstantDecl>()) {
8624*67e74705SXin Li // Don't provide a fixit outside C++11 mode; we don't want to suggest
8625*67e74705SXin Li // repeating the type of the enumeration here, and we can't do so if
8626*67e74705SXin Li // the type is anonymous.
8627*67e74705SXin Li FixItHint FixIt;
8628*67e74705SXin Li if (getLangOpts().CPlusPlus11) {
8629*67e74705SXin Li // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8630*67e74705SXin Li FixIt = FixItHint::CreateReplacement(
8631*67e74705SXin Li UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
8632*67e74705SXin Li }
8633*67e74705SXin Li
8634*67e74705SXin Li Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8635*67e74705SXin Li << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
8636*67e74705SXin Li << FixIt;
8637*67e74705SXin Li }
8638*67e74705SXin Li return true;
8639*67e74705SXin Li }
8640*67e74705SXin Li
8641*67e74705SXin Li // Otherwise, everything is known to be fine.
8642*67e74705SXin Li return false;
8643*67e74705SXin Li }
8644*67e74705SXin Li
8645*67e74705SXin Li // The current scope is a record.
8646*67e74705SXin Li
8647*67e74705SXin Li // If the named context is dependent, we can't decide much.
8648*67e74705SXin Li if (!NamedContext) {
8649*67e74705SXin Li // FIXME: in C++0x, we can diagnose if we can prove that the
8650*67e74705SXin Li // nested-name-specifier does not refer to a base class, which is
8651*67e74705SXin Li // still possible in some cases.
8652*67e74705SXin Li
8653*67e74705SXin Li // Otherwise we have to conservatively report that things might be
8654*67e74705SXin Li // okay.
8655*67e74705SXin Li return false;
8656*67e74705SXin Li }
8657*67e74705SXin Li
8658*67e74705SXin Li if (!NamedContext->isRecord()) {
8659*67e74705SXin Li // Ideally this would point at the last name in the specifier,
8660*67e74705SXin Li // but we don't have that level of source info.
8661*67e74705SXin Li Diag(SS.getRange().getBegin(),
8662*67e74705SXin Li diag::err_using_decl_nested_name_specifier_is_not_class)
8663*67e74705SXin Li << SS.getScopeRep() << SS.getRange();
8664*67e74705SXin Li return true;
8665*67e74705SXin Li }
8666*67e74705SXin Li
8667*67e74705SXin Li if (!NamedContext->isDependentContext() &&
8668*67e74705SXin Li RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8669*67e74705SXin Li return true;
8670*67e74705SXin Li
8671*67e74705SXin Li if (getLangOpts().CPlusPlus11) {
8672*67e74705SXin Li // C++11 [namespace.udecl]p3:
8673*67e74705SXin Li // In a using-declaration used as a member-declaration, the
8674*67e74705SXin Li // nested-name-specifier shall name a base class of the class
8675*67e74705SXin Li // being defined.
8676*67e74705SXin Li
8677*67e74705SXin Li if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8678*67e74705SXin Li cast<CXXRecordDecl>(NamedContext))) {
8679*67e74705SXin Li if (CurContext == NamedContext) {
8680*67e74705SXin Li Diag(NameLoc,
8681*67e74705SXin Li diag::err_using_decl_nested_name_specifier_is_current_class)
8682*67e74705SXin Li << SS.getRange();
8683*67e74705SXin Li return true;
8684*67e74705SXin Li }
8685*67e74705SXin Li
8686*67e74705SXin Li Diag(SS.getRange().getBegin(),
8687*67e74705SXin Li diag::err_using_decl_nested_name_specifier_is_not_base_class)
8688*67e74705SXin Li << SS.getScopeRep()
8689*67e74705SXin Li << cast<CXXRecordDecl>(CurContext)
8690*67e74705SXin Li << SS.getRange();
8691*67e74705SXin Li return true;
8692*67e74705SXin Li }
8693*67e74705SXin Li
8694*67e74705SXin Li return false;
8695*67e74705SXin Li }
8696*67e74705SXin Li
8697*67e74705SXin Li // C++03 [namespace.udecl]p4:
8698*67e74705SXin Li // A using-declaration used as a member-declaration shall refer
8699*67e74705SXin Li // to a member of a base class of the class being defined [etc.].
8700*67e74705SXin Li
8701*67e74705SXin Li // Salient point: SS doesn't have to name a base class as long as
8702*67e74705SXin Li // lookup only finds members from base classes. Therefore we can
8703*67e74705SXin Li // diagnose here only if we can prove that that can't happen,
8704*67e74705SXin Li // i.e. if the class hierarchies provably don't intersect.
8705*67e74705SXin Li
8706*67e74705SXin Li // TODO: it would be nice if "definitely valid" results were cached
8707*67e74705SXin Li // in the UsingDecl and UsingShadowDecl so that these checks didn't
8708*67e74705SXin Li // need to be repeated.
8709*67e74705SXin Li
8710*67e74705SXin Li llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8711*67e74705SXin Li auto Collect = [&Bases](const CXXRecordDecl *Base) {
8712*67e74705SXin Li Bases.insert(Base);
8713*67e74705SXin Li return true;
8714*67e74705SXin Li };
8715*67e74705SXin Li
8716*67e74705SXin Li // Collect all bases. Return false if we find a dependent base.
8717*67e74705SXin Li if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
8718*67e74705SXin Li return false;
8719*67e74705SXin Li
8720*67e74705SXin Li // Returns true if the base is dependent or is one of the accumulated base
8721*67e74705SXin Li // classes.
8722*67e74705SXin Li auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8723*67e74705SXin Li return !Bases.count(Base);
8724*67e74705SXin Li };
8725*67e74705SXin Li
8726*67e74705SXin Li // Return false if the class has a dependent base or if it or one
8727*67e74705SXin Li // of its bases is present in the base set of the current context.
8728*67e74705SXin Li if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8729*67e74705SXin Li !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
8730*67e74705SXin Li return false;
8731*67e74705SXin Li
8732*67e74705SXin Li Diag(SS.getRange().getBegin(),
8733*67e74705SXin Li diag::err_using_decl_nested_name_specifier_is_not_base_class)
8734*67e74705SXin Li << SS.getScopeRep()
8735*67e74705SXin Li << cast<CXXRecordDecl>(CurContext)
8736*67e74705SXin Li << SS.getRange();
8737*67e74705SXin Li
8738*67e74705SXin Li return true;
8739*67e74705SXin Li }
8740*67e74705SXin Li
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,AttributeList * AttrList,TypeResult Type,Decl * DeclFromDeclSpec)8741*67e74705SXin Li Decl *Sema::ActOnAliasDeclaration(Scope *S,
8742*67e74705SXin Li AccessSpecifier AS,
8743*67e74705SXin Li MultiTemplateParamsArg TemplateParamLists,
8744*67e74705SXin Li SourceLocation UsingLoc,
8745*67e74705SXin Li UnqualifiedId &Name,
8746*67e74705SXin Li AttributeList *AttrList,
8747*67e74705SXin Li TypeResult Type,
8748*67e74705SXin Li Decl *DeclFromDeclSpec) {
8749*67e74705SXin Li // Skip up to the relevant declaration scope.
8750*67e74705SXin Li while (S->isTemplateParamScope())
8751*67e74705SXin Li S = S->getParent();
8752*67e74705SXin Li assert((S->getFlags() & Scope::DeclScope) &&
8753*67e74705SXin Li "got alias-declaration outside of declaration scope");
8754*67e74705SXin Li
8755*67e74705SXin Li if (Type.isInvalid())
8756*67e74705SXin Li return nullptr;
8757*67e74705SXin Li
8758*67e74705SXin Li bool Invalid = false;
8759*67e74705SXin Li DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8760*67e74705SXin Li TypeSourceInfo *TInfo = nullptr;
8761*67e74705SXin Li GetTypeFromParser(Type.get(), &TInfo);
8762*67e74705SXin Li
8763*67e74705SXin Li if (DiagnoseClassNameShadow(CurContext, NameInfo))
8764*67e74705SXin Li return nullptr;
8765*67e74705SXin Li
8766*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8767*67e74705SXin Li UPPC_DeclarationType)) {
8768*67e74705SXin Li Invalid = true;
8769*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8770*67e74705SXin Li TInfo->getTypeLoc().getBeginLoc());
8771*67e74705SXin Li }
8772*67e74705SXin Li
8773*67e74705SXin Li LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8774*67e74705SXin Li LookupName(Previous, S);
8775*67e74705SXin Li
8776*67e74705SXin Li // Warn about shadowing the name of a template parameter.
8777*67e74705SXin Li if (Previous.isSingleResult() &&
8778*67e74705SXin Li Previous.getFoundDecl()->isTemplateParameter()) {
8779*67e74705SXin Li DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8780*67e74705SXin Li Previous.clear();
8781*67e74705SXin Li }
8782*67e74705SXin Li
8783*67e74705SXin Li assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8784*67e74705SXin Li "name in alias declaration must be an identifier");
8785*67e74705SXin Li TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8786*67e74705SXin Li Name.StartLocation,
8787*67e74705SXin Li Name.Identifier, TInfo);
8788*67e74705SXin Li
8789*67e74705SXin Li NewTD->setAccess(AS);
8790*67e74705SXin Li
8791*67e74705SXin Li if (Invalid)
8792*67e74705SXin Li NewTD->setInvalidDecl();
8793*67e74705SXin Li
8794*67e74705SXin Li ProcessDeclAttributeList(S, NewTD, AttrList);
8795*67e74705SXin Li
8796*67e74705SXin Li CheckTypedefForVariablyModifiedType(S, NewTD);
8797*67e74705SXin Li Invalid |= NewTD->isInvalidDecl();
8798*67e74705SXin Li
8799*67e74705SXin Li bool Redeclaration = false;
8800*67e74705SXin Li
8801*67e74705SXin Li NamedDecl *NewND;
8802*67e74705SXin Li if (TemplateParamLists.size()) {
8803*67e74705SXin Li TypeAliasTemplateDecl *OldDecl = nullptr;
8804*67e74705SXin Li TemplateParameterList *OldTemplateParams = nullptr;
8805*67e74705SXin Li
8806*67e74705SXin Li if (TemplateParamLists.size() != 1) {
8807*67e74705SXin Li Diag(UsingLoc, diag::err_alias_template_extra_headers)
8808*67e74705SXin Li << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8809*67e74705SXin Li TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8810*67e74705SXin Li }
8811*67e74705SXin Li TemplateParameterList *TemplateParams = TemplateParamLists[0];
8812*67e74705SXin Li
8813*67e74705SXin Li // Check that we can declare a template here.
8814*67e74705SXin Li if (CheckTemplateDeclScope(S, TemplateParams))
8815*67e74705SXin Li return nullptr;
8816*67e74705SXin Li
8817*67e74705SXin Li // Only consider previous declarations in the same scope.
8818*67e74705SXin Li FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8819*67e74705SXin Li /*ExplicitInstantiationOrSpecialization*/false);
8820*67e74705SXin Li if (!Previous.empty()) {
8821*67e74705SXin Li Redeclaration = true;
8822*67e74705SXin Li
8823*67e74705SXin Li OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8824*67e74705SXin Li if (!OldDecl && !Invalid) {
8825*67e74705SXin Li Diag(UsingLoc, diag::err_redefinition_different_kind)
8826*67e74705SXin Li << Name.Identifier;
8827*67e74705SXin Li
8828*67e74705SXin Li NamedDecl *OldD = Previous.getRepresentativeDecl();
8829*67e74705SXin Li if (OldD->getLocation().isValid())
8830*67e74705SXin Li Diag(OldD->getLocation(), diag::note_previous_definition);
8831*67e74705SXin Li
8832*67e74705SXin Li Invalid = true;
8833*67e74705SXin Li }
8834*67e74705SXin Li
8835*67e74705SXin Li if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8836*67e74705SXin Li if (TemplateParameterListsAreEqual(TemplateParams,
8837*67e74705SXin Li OldDecl->getTemplateParameters(),
8838*67e74705SXin Li /*Complain=*/true,
8839*67e74705SXin Li TPL_TemplateMatch))
8840*67e74705SXin Li OldTemplateParams = OldDecl->getTemplateParameters();
8841*67e74705SXin Li else
8842*67e74705SXin Li Invalid = true;
8843*67e74705SXin Li
8844*67e74705SXin Li TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8845*67e74705SXin Li if (!Invalid &&
8846*67e74705SXin Li !Context.hasSameType(OldTD->getUnderlyingType(),
8847*67e74705SXin Li NewTD->getUnderlyingType())) {
8848*67e74705SXin Li // FIXME: The C++0x standard does not clearly say this is ill-formed,
8849*67e74705SXin Li // but we can't reasonably accept it.
8850*67e74705SXin Li Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8851*67e74705SXin Li << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8852*67e74705SXin Li if (OldTD->getLocation().isValid())
8853*67e74705SXin Li Diag(OldTD->getLocation(), diag::note_previous_definition);
8854*67e74705SXin Li Invalid = true;
8855*67e74705SXin Li }
8856*67e74705SXin Li }
8857*67e74705SXin Li }
8858*67e74705SXin Li
8859*67e74705SXin Li // Merge any previous default template arguments into our parameters,
8860*67e74705SXin Li // and check the parameter list.
8861*67e74705SXin Li if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8862*67e74705SXin Li TPC_TypeAliasTemplate))
8863*67e74705SXin Li return nullptr;
8864*67e74705SXin Li
8865*67e74705SXin Li TypeAliasTemplateDecl *NewDecl =
8866*67e74705SXin Li TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8867*67e74705SXin Li Name.Identifier, TemplateParams,
8868*67e74705SXin Li NewTD);
8869*67e74705SXin Li NewTD->setDescribedAliasTemplate(NewDecl);
8870*67e74705SXin Li
8871*67e74705SXin Li NewDecl->setAccess(AS);
8872*67e74705SXin Li
8873*67e74705SXin Li if (Invalid)
8874*67e74705SXin Li NewDecl->setInvalidDecl();
8875*67e74705SXin Li else if (OldDecl)
8876*67e74705SXin Li NewDecl->setPreviousDecl(OldDecl);
8877*67e74705SXin Li
8878*67e74705SXin Li NewND = NewDecl;
8879*67e74705SXin Li } else {
8880*67e74705SXin Li if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8881*67e74705SXin Li setTagNameForLinkagePurposes(TD, NewTD);
8882*67e74705SXin Li handleTagNumbering(TD, S);
8883*67e74705SXin Li }
8884*67e74705SXin Li ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8885*67e74705SXin Li NewND = NewTD;
8886*67e74705SXin Li }
8887*67e74705SXin Li
8888*67e74705SXin Li if (!Redeclaration)
8889*67e74705SXin Li PushOnScopeChains(NewND, S);
8890*67e74705SXin Li
8891*67e74705SXin Li ActOnDocumentableDecl(NewND);
8892*67e74705SXin Li return NewND;
8893*67e74705SXin Li }
8894*67e74705SXin Li
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)8895*67e74705SXin Li Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8896*67e74705SXin Li SourceLocation AliasLoc,
8897*67e74705SXin Li IdentifierInfo *Alias, CXXScopeSpec &SS,
8898*67e74705SXin Li SourceLocation IdentLoc,
8899*67e74705SXin Li IdentifierInfo *Ident) {
8900*67e74705SXin Li
8901*67e74705SXin Li // Lookup the namespace name.
8902*67e74705SXin Li LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8903*67e74705SXin Li LookupParsedName(R, S, &SS);
8904*67e74705SXin Li
8905*67e74705SXin Li if (R.isAmbiguous())
8906*67e74705SXin Li return nullptr;
8907*67e74705SXin Li
8908*67e74705SXin Li if (R.empty()) {
8909*67e74705SXin Li if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8910*67e74705SXin Li Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8911*67e74705SXin Li return nullptr;
8912*67e74705SXin Li }
8913*67e74705SXin Li }
8914*67e74705SXin Li assert(!R.isAmbiguous() && !R.empty());
8915*67e74705SXin Li NamedDecl *ND = R.getRepresentativeDecl();
8916*67e74705SXin Li
8917*67e74705SXin Li // Check if we have a previous declaration with the same name.
8918*67e74705SXin Li LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8919*67e74705SXin Li ForRedeclaration);
8920*67e74705SXin Li LookupName(PrevR, S);
8921*67e74705SXin Li
8922*67e74705SXin Li // Check we're not shadowing a template parameter.
8923*67e74705SXin Li if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8924*67e74705SXin Li DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8925*67e74705SXin Li PrevR.clear();
8926*67e74705SXin Li }
8927*67e74705SXin Li
8928*67e74705SXin Li // Filter out any other lookup result from an enclosing scope.
8929*67e74705SXin Li FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8930*67e74705SXin Li /*AllowInlineNamespace*/false);
8931*67e74705SXin Li
8932*67e74705SXin Li // Find the previous declaration and check that we can redeclare it.
8933*67e74705SXin Li NamespaceAliasDecl *Prev = nullptr;
8934*67e74705SXin Li if (PrevR.isSingleResult()) {
8935*67e74705SXin Li NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
8936*67e74705SXin Li if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8937*67e74705SXin Li // We already have an alias with the same name that points to the same
8938*67e74705SXin Li // namespace; check that it matches.
8939*67e74705SXin Li if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8940*67e74705SXin Li Prev = AD;
8941*67e74705SXin Li } else if (isVisible(PrevDecl)) {
8942*67e74705SXin Li Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8943*67e74705SXin Li << Alias;
8944*67e74705SXin Li Diag(AD->getLocation(), diag::note_previous_namespace_alias)
8945*67e74705SXin Li << AD->getNamespace();
8946*67e74705SXin Li return nullptr;
8947*67e74705SXin Li }
8948*67e74705SXin Li } else if (isVisible(PrevDecl)) {
8949*67e74705SXin Li unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
8950*67e74705SXin Li ? diag::err_redefinition
8951*67e74705SXin Li : diag::err_redefinition_different_kind;
8952*67e74705SXin Li Diag(AliasLoc, DiagID) << Alias;
8953*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8954*67e74705SXin Li return nullptr;
8955*67e74705SXin Li }
8956*67e74705SXin Li }
8957*67e74705SXin Li
8958*67e74705SXin Li // The use of a nested name specifier may trigger deprecation warnings.
8959*67e74705SXin Li DiagnoseUseOfDecl(ND, IdentLoc);
8960*67e74705SXin Li
8961*67e74705SXin Li NamespaceAliasDecl *AliasDecl =
8962*67e74705SXin Li NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8963*67e74705SXin Li Alias, SS.getWithLocInContext(Context),
8964*67e74705SXin Li IdentLoc, ND);
8965*67e74705SXin Li if (Prev)
8966*67e74705SXin Li AliasDecl->setPreviousDecl(Prev);
8967*67e74705SXin Li
8968*67e74705SXin Li PushOnScopeChains(AliasDecl, S);
8969*67e74705SXin Li return AliasDecl;
8970*67e74705SXin Li }
8971*67e74705SXin Li
8972*67e74705SXin Li Sema::ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,CXXMethodDecl * MD)8973*67e74705SXin Li Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8974*67e74705SXin Li CXXMethodDecl *MD) {
8975*67e74705SXin Li CXXRecordDecl *ClassDecl = MD->getParent();
8976*67e74705SXin Li
8977*67e74705SXin Li // C++ [except.spec]p14:
8978*67e74705SXin Li // An implicitly declared special member function (Clause 12) shall have an
8979*67e74705SXin Li // exception-specification. [...]
8980*67e74705SXin Li ImplicitExceptionSpecification ExceptSpec(*this);
8981*67e74705SXin Li if (ClassDecl->isInvalidDecl())
8982*67e74705SXin Li return ExceptSpec;
8983*67e74705SXin Li
8984*67e74705SXin Li // Direct base-class constructors.
8985*67e74705SXin Li for (const auto &B : ClassDecl->bases()) {
8986*67e74705SXin Li if (B.isVirtual()) // Handled below.
8987*67e74705SXin Li continue;
8988*67e74705SXin Li
8989*67e74705SXin Li if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8990*67e74705SXin Li CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8991*67e74705SXin Li CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8992*67e74705SXin Li // If this is a deleted function, add it anyway. This might be conformant
8993*67e74705SXin Li // with the standard. This might not. I'm not sure. It might not matter.
8994*67e74705SXin Li if (Constructor)
8995*67e74705SXin Li ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8996*67e74705SXin Li }
8997*67e74705SXin Li }
8998*67e74705SXin Li
8999*67e74705SXin Li // Virtual base-class constructors.
9000*67e74705SXin Li for (const auto &B : ClassDecl->vbases()) {
9001*67e74705SXin Li if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9002*67e74705SXin Li CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9003*67e74705SXin Li CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9004*67e74705SXin Li // If this is a deleted function, add it anyway. This might be conformant
9005*67e74705SXin Li // with the standard. This might not. I'm not sure. It might not matter.
9006*67e74705SXin Li if (Constructor)
9007*67e74705SXin Li ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9008*67e74705SXin Li }
9009*67e74705SXin Li }
9010*67e74705SXin Li
9011*67e74705SXin Li // Field constructors.
9012*67e74705SXin Li for (const auto *F : ClassDecl->fields()) {
9013*67e74705SXin Li if (F->hasInClassInitializer()) {
9014*67e74705SXin Li if (Expr *E = F->getInClassInitializer())
9015*67e74705SXin Li ExceptSpec.CalledExpr(E);
9016*67e74705SXin Li } else if (const RecordType *RecordTy
9017*67e74705SXin Li = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9018*67e74705SXin Li CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9019*67e74705SXin Li CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9020*67e74705SXin Li // If this is a deleted function, add it anyway. This might be conformant
9021*67e74705SXin Li // with the standard. This might not. I'm not sure. It might not matter.
9022*67e74705SXin Li // In particular, the problem is that this function never gets called. It
9023*67e74705SXin Li // might just be ill-formed because this function attempts to refer to
9024*67e74705SXin Li // a deleted function here.
9025*67e74705SXin Li if (Constructor)
9026*67e74705SXin Li ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9027*67e74705SXin Li }
9028*67e74705SXin Li }
9029*67e74705SXin Li
9030*67e74705SXin Li return ExceptSpec;
9031*67e74705SXin Li }
9032*67e74705SXin Li
9033*67e74705SXin Li Sema::ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(SourceLocation Loc,CXXConstructorDecl * CD)9034*67e74705SXin Li Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9035*67e74705SXin Li CXXConstructorDecl *CD) {
9036*67e74705SXin Li CXXRecordDecl *ClassDecl = CD->getParent();
9037*67e74705SXin Li
9038*67e74705SXin Li // C++ [except.spec]p14:
9039*67e74705SXin Li // An inheriting constructor [...] shall have an exception-specification. [...]
9040*67e74705SXin Li ImplicitExceptionSpecification ExceptSpec(*this);
9041*67e74705SXin Li if (ClassDecl->isInvalidDecl())
9042*67e74705SXin Li return ExceptSpec;
9043*67e74705SXin Li
9044*67e74705SXin Li auto Inherited = CD->getInheritedConstructor();
9045*67e74705SXin Li InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
9046*67e74705SXin Li
9047*67e74705SXin Li // Direct and virtual base-class constructors.
9048*67e74705SXin Li for (bool VBase : {false, true}) {
9049*67e74705SXin Li for (CXXBaseSpecifier &B :
9050*67e74705SXin Li VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9051*67e74705SXin Li // Don't visit direct vbases twice.
9052*67e74705SXin Li if (B.isVirtual() != VBase)
9053*67e74705SXin Li continue;
9054*67e74705SXin Li
9055*67e74705SXin Li CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9056*67e74705SXin Li if (!BaseClass)
9057*67e74705SXin Li continue;
9058*67e74705SXin Li
9059*67e74705SXin Li CXXConstructorDecl *Constructor =
9060*67e74705SXin Li ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9061*67e74705SXin Li .first;
9062*67e74705SXin Li if (!Constructor)
9063*67e74705SXin Li Constructor = LookupDefaultConstructor(BaseClass);
9064*67e74705SXin Li if (Constructor)
9065*67e74705SXin Li ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9066*67e74705SXin Li }
9067*67e74705SXin Li }
9068*67e74705SXin Li
9069*67e74705SXin Li // Field constructors.
9070*67e74705SXin Li for (const auto *F : ClassDecl->fields()) {
9071*67e74705SXin Li if (F->hasInClassInitializer()) {
9072*67e74705SXin Li if (Expr *E = F->getInClassInitializer())
9073*67e74705SXin Li ExceptSpec.CalledExpr(E);
9074*67e74705SXin Li } else if (const RecordType *RecordTy
9075*67e74705SXin Li = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9076*67e74705SXin Li CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9077*67e74705SXin Li CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9078*67e74705SXin Li if (Constructor)
9079*67e74705SXin Li ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9080*67e74705SXin Li }
9081*67e74705SXin Li }
9082*67e74705SXin Li
9083*67e74705SXin Li return ExceptSpec;
9084*67e74705SXin Li }
9085*67e74705SXin Li
9086*67e74705SXin Li namespace {
9087*67e74705SXin Li /// RAII object to register a special member as being currently declared.
9088*67e74705SXin Li struct DeclaringSpecialMember {
9089*67e74705SXin Li Sema &S;
9090*67e74705SXin Li Sema::SpecialMemberDecl D;
9091*67e74705SXin Li Sema::ContextRAII SavedContext;
9092*67e74705SXin Li bool WasAlreadyBeingDeclared;
9093*67e74705SXin Li
DeclaringSpecialMember__anon75252e181011::DeclaringSpecialMember9094*67e74705SXin Li DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
9095*67e74705SXin Li : S(S), D(RD, CSM), SavedContext(S, RD) {
9096*67e74705SXin Li WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
9097*67e74705SXin Li if (WasAlreadyBeingDeclared)
9098*67e74705SXin Li // This almost never happens, but if it does, ensure that our cache
9099*67e74705SXin Li // doesn't contain a stale result.
9100*67e74705SXin Li S.SpecialMemberCache.clear();
9101*67e74705SXin Li
9102*67e74705SXin Li // FIXME: Register a note to be produced if we encounter an error while
9103*67e74705SXin Li // declaring the special member.
9104*67e74705SXin Li }
~DeclaringSpecialMember__anon75252e181011::DeclaringSpecialMember9105*67e74705SXin Li ~DeclaringSpecialMember() {
9106*67e74705SXin Li if (!WasAlreadyBeingDeclared)
9107*67e74705SXin Li S.SpecialMembersBeingDeclared.erase(D);
9108*67e74705SXin Li }
9109*67e74705SXin Li
9110*67e74705SXin Li /// \brief Are we already trying to declare this special member?
isAlreadyBeingDeclared__anon75252e181011::DeclaringSpecialMember9111*67e74705SXin Li bool isAlreadyBeingDeclared() const {
9112*67e74705SXin Li return WasAlreadyBeingDeclared;
9113*67e74705SXin Li }
9114*67e74705SXin Li };
9115*67e74705SXin Li }
9116*67e74705SXin Li
CheckImplicitSpecialMemberDeclaration(Scope * S,FunctionDecl * FD)9117*67e74705SXin Li void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9118*67e74705SXin Li // Look up any existing declarations, but don't trigger declaration of all
9119*67e74705SXin Li // implicit special members with this name.
9120*67e74705SXin Li DeclarationName Name = FD->getDeclName();
9121*67e74705SXin Li LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9122*67e74705SXin Li ForRedeclaration);
9123*67e74705SXin Li for (auto *D : FD->getParent()->lookup(Name))
9124*67e74705SXin Li if (auto *Acceptable = R.getAcceptableDecl(D))
9125*67e74705SXin Li R.addDecl(Acceptable);
9126*67e74705SXin Li R.resolveKind();
9127*67e74705SXin Li R.suppressDiagnostics();
9128*67e74705SXin Li
9129*67e74705SXin Li CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9130*67e74705SXin Li }
9131*67e74705SXin Li
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)9132*67e74705SXin Li CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9133*67e74705SXin Li CXXRecordDecl *ClassDecl) {
9134*67e74705SXin Li // C++ [class.ctor]p5:
9135*67e74705SXin Li // A default constructor for a class X is a constructor of class X
9136*67e74705SXin Li // that can be called without an argument. If there is no
9137*67e74705SXin Li // user-declared constructor for class X, a default constructor is
9138*67e74705SXin Li // implicitly declared. An implicitly-declared default constructor
9139*67e74705SXin Li // is an inline public member of its class.
9140*67e74705SXin Li assert(ClassDecl->needsImplicitDefaultConstructor() &&
9141*67e74705SXin Li "Should not build implicit default constructor!");
9142*67e74705SXin Li
9143*67e74705SXin Li DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9144*67e74705SXin Li if (DSM.isAlreadyBeingDeclared())
9145*67e74705SXin Li return nullptr;
9146*67e74705SXin Li
9147*67e74705SXin Li bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9148*67e74705SXin Li CXXDefaultConstructor,
9149*67e74705SXin Li false);
9150*67e74705SXin Li
9151*67e74705SXin Li // Create the actual constructor declaration.
9152*67e74705SXin Li CanQualType ClassType
9153*67e74705SXin Li = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9154*67e74705SXin Li SourceLocation ClassLoc = ClassDecl->getLocation();
9155*67e74705SXin Li DeclarationName Name
9156*67e74705SXin Li = Context.DeclarationNames.getCXXConstructorName(ClassType);
9157*67e74705SXin Li DeclarationNameInfo NameInfo(Name, ClassLoc);
9158*67e74705SXin Li CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
9159*67e74705SXin Li Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9160*67e74705SXin Li /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9161*67e74705SXin Li /*isImplicitlyDeclared=*/true, Constexpr);
9162*67e74705SXin Li DefaultCon->setAccess(AS_public);
9163*67e74705SXin Li DefaultCon->setDefaulted();
9164*67e74705SXin Li
9165*67e74705SXin Li if (getLangOpts().CUDA) {
9166*67e74705SXin Li inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9167*67e74705SXin Li DefaultCon,
9168*67e74705SXin Li /* ConstRHS */ false,
9169*67e74705SXin Li /* Diagnose */ false);
9170*67e74705SXin Li }
9171*67e74705SXin Li
9172*67e74705SXin Li // Build an exception specification pointing back at this constructor.
9173*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
9174*67e74705SXin Li DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9175*67e74705SXin Li
9176*67e74705SXin Li // We don't need to use SpecialMemberIsTrivial here; triviality for default
9177*67e74705SXin Li // constructors is easy to compute.
9178*67e74705SXin Li DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9179*67e74705SXin Li
9180*67e74705SXin Li // Note that we have declared this constructor.
9181*67e74705SXin Li ++ASTContext::NumImplicitDefaultConstructorsDeclared;
9182*67e74705SXin Li
9183*67e74705SXin Li Scope *S = getScopeForContext(ClassDecl);
9184*67e74705SXin Li CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9185*67e74705SXin Li
9186*67e74705SXin Li if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9187*67e74705SXin Li SetDeclDeleted(DefaultCon, ClassLoc);
9188*67e74705SXin Li
9189*67e74705SXin Li if (S)
9190*67e74705SXin Li PushOnScopeChains(DefaultCon, S, false);
9191*67e74705SXin Li ClassDecl->addDecl(DefaultCon);
9192*67e74705SXin Li
9193*67e74705SXin Li return DefaultCon;
9194*67e74705SXin Li }
9195*67e74705SXin Li
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)9196*67e74705SXin Li void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9197*67e74705SXin Li CXXConstructorDecl *Constructor) {
9198*67e74705SXin Li assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
9199*67e74705SXin Li !Constructor->doesThisDeclarationHaveABody() &&
9200*67e74705SXin Li !Constructor->isDeleted()) &&
9201*67e74705SXin Li "DefineImplicitDefaultConstructor - call it for implicit default ctor");
9202*67e74705SXin Li
9203*67e74705SXin Li CXXRecordDecl *ClassDecl = Constructor->getParent();
9204*67e74705SXin Li assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
9205*67e74705SXin Li
9206*67e74705SXin Li SynthesizedFunctionScope Scope(*this, Constructor);
9207*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
9208*67e74705SXin Li if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9209*67e74705SXin Li Trap.hasErrorOccurred()) {
9210*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
9211*67e74705SXin Li << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
9212*67e74705SXin Li Constructor->setInvalidDecl();
9213*67e74705SXin Li return;
9214*67e74705SXin Li }
9215*67e74705SXin Li
9216*67e74705SXin Li // The exception specification is needed because we are defining the
9217*67e74705SXin Li // function.
9218*67e74705SXin Li ResolveExceptionSpec(CurrentLocation,
9219*67e74705SXin Li Constructor->getType()->castAs<FunctionProtoType>());
9220*67e74705SXin Li
9221*67e74705SXin Li SourceLocation Loc = Constructor->getLocEnd().isValid()
9222*67e74705SXin Li ? Constructor->getLocEnd()
9223*67e74705SXin Li : Constructor->getLocation();
9224*67e74705SXin Li Constructor->setBody(new (Context) CompoundStmt(Loc));
9225*67e74705SXin Li
9226*67e74705SXin Li Constructor->markUsed(Context);
9227*67e74705SXin Li MarkVTableUsed(CurrentLocation, ClassDecl);
9228*67e74705SXin Li
9229*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
9230*67e74705SXin Li L->CompletedImplicitDefinition(Constructor);
9231*67e74705SXin Li }
9232*67e74705SXin Li
9233*67e74705SXin Li DiagnoseUninitializedFields(*this, Constructor);
9234*67e74705SXin Li }
9235*67e74705SXin Li
ActOnFinishDelayedMemberInitializers(Decl * D)9236*67e74705SXin Li void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
9237*67e74705SXin Li // Perform any delayed checks on exception specifications.
9238*67e74705SXin Li CheckDelayedMemberExceptionSpecs();
9239*67e74705SXin Li }
9240*67e74705SXin Li
9241*67e74705SXin Li /// Find or create the fake constructor we synthesize to model constructing an
9242*67e74705SXin Li /// object of a derived class via a constructor of a base class.
9243*67e74705SXin Li CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc,CXXConstructorDecl * BaseCtor,ConstructorUsingShadowDecl * Shadow)9244*67e74705SXin Li Sema::findInheritingConstructor(SourceLocation Loc,
9245*67e74705SXin Li CXXConstructorDecl *BaseCtor,
9246*67e74705SXin Li ConstructorUsingShadowDecl *Shadow) {
9247*67e74705SXin Li CXXRecordDecl *Derived = Shadow->getParent();
9248*67e74705SXin Li SourceLocation UsingLoc = Shadow->getLocation();
9249*67e74705SXin Li
9250*67e74705SXin Li // FIXME: Add a new kind of DeclarationName for an inherited constructor.
9251*67e74705SXin Li // For now we use the name of the base class constructor as a member of the
9252*67e74705SXin Li // derived class to indicate a (fake) inherited constructor name.
9253*67e74705SXin Li DeclarationName Name = BaseCtor->getDeclName();
9254*67e74705SXin Li
9255*67e74705SXin Li // Check to see if we already have a fake constructor for this inherited
9256*67e74705SXin Li // constructor call.
9257*67e74705SXin Li for (NamedDecl *Ctor : Derived->lookup(Name))
9258*67e74705SXin Li if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
9259*67e74705SXin Li ->getInheritedConstructor()
9260*67e74705SXin Li .getConstructor(),
9261*67e74705SXin Li BaseCtor))
9262*67e74705SXin Li return cast<CXXConstructorDecl>(Ctor);
9263*67e74705SXin Li
9264*67e74705SXin Li DeclarationNameInfo NameInfo(Name, UsingLoc);
9265*67e74705SXin Li TypeSourceInfo *TInfo =
9266*67e74705SXin Li Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
9267*67e74705SXin Li FunctionProtoTypeLoc ProtoLoc =
9268*67e74705SXin Li TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9269*67e74705SXin Li
9270*67e74705SXin Li // Check the inherited constructor is valid and find the list of base classes
9271*67e74705SXin Li // from which it was inherited.
9272*67e74705SXin Li InheritedConstructorInfo ICI(*this, Loc, Shadow);
9273*67e74705SXin Li
9274*67e74705SXin Li bool Constexpr =
9275*67e74705SXin Li BaseCtor->isConstexpr() &&
9276*67e74705SXin Li defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
9277*67e74705SXin Li false, BaseCtor, &ICI);
9278*67e74705SXin Li
9279*67e74705SXin Li CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9280*67e74705SXin Li Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
9281*67e74705SXin Li BaseCtor->isExplicit(), /*Inline=*/true,
9282*67e74705SXin Li /*ImplicitlyDeclared=*/true, Constexpr,
9283*67e74705SXin Li InheritedConstructor(Shadow, BaseCtor));
9284*67e74705SXin Li if (Shadow->isInvalidDecl())
9285*67e74705SXin Li DerivedCtor->setInvalidDecl();
9286*67e74705SXin Li
9287*67e74705SXin Li // Build an unevaluated exception specification for this fake constructor.
9288*67e74705SXin Li const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
9289*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9290*67e74705SXin Li EPI.ExceptionSpec.Type = EST_Unevaluated;
9291*67e74705SXin Li EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9292*67e74705SXin Li DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9293*67e74705SXin Li FPT->getParamTypes(), EPI));
9294*67e74705SXin Li
9295*67e74705SXin Li // Build the parameter declarations.
9296*67e74705SXin Li SmallVector<ParmVarDecl *, 16> ParamDecls;
9297*67e74705SXin Li for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9298*67e74705SXin Li TypeSourceInfo *TInfo =
9299*67e74705SXin Li Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9300*67e74705SXin Li ParmVarDecl *PD = ParmVarDecl::Create(
9301*67e74705SXin Li Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9302*67e74705SXin Li FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9303*67e74705SXin Li PD->setScopeInfo(0, I);
9304*67e74705SXin Li PD->setImplicit();
9305*67e74705SXin Li // Ensure attributes are propagated onto parameters (this matters for
9306*67e74705SXin Li // format, pass_object_size, ...).
9307*67e74705SXin Li mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
9308*67e74705SXin Li ParamDecls.push_back(PD);
9309*67e74705SXin Li ProtoLoc.setParam(I, PD);
9310*67e74705SXin Li }
9311*67e74705SXin Li
9312*67e74705SXin Li // Set up the new constructor.
9313*67e74705SXin Li assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
9314*67e74705SXin Li DerivedCtor->setAccess(BaseCtor->getAccess());
9315*67e74705SXin Li DerivedCtor->setParams(ParamDecls);
9316*67e74705SXin Li Derived->addDecl(DerivedCtor);
9317*67e74705SXin Li
9318*67e74705SXin Li if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
9319*67e74705SXin Li SetDeclDeleted(DerivedCtor, UsingLoc);
9320*67e74705SXin Li
9321*67e74705SXin Li return DerivedCtor;
9322*67e74705SXin Li }
9323*67e74705SXin Li
NoteDeletedInheritingConstructor(CXXConstructorDecl * Ctor)9324*67e74705SXin Li void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
9325*67e74705SXin Li InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
9326*67e74705SXin Li Ctor->getInheritedConstructor().getShadowDecl());
9327*67e74705SXin Li ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
9328*67e74705SXin Li /*Diagnose*/true);
9329*67e74705SXin Li }
9330*67e74705SXin Li
DefineInheritingConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)9331*67e74705SXin Li void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9332*67e74705SXin Li CXXConstructorDecl *Constructor) {
9333*67e74705SXin Li CXXRecordDecl *ClassDecl = Constructor->getParent();
9334*67e74705SXin Li assert(Constructor->getInheritedConstructor() &&
9335*67e74705SXin Li !Constructor->doesThisDeclarationHaveABody() &&
9336*67e74705SXin Li !Constructor->isDeleted());
9337*67e74705SXin Li if (Constructor->isInvalidDecl())
9338*67e74705SXin Li return;
9339*67e74705SXin Li
9340*67e74705SXin Li ConstructorUsingShadowDecl *Shadow =
9341*67e74705SXin Li Constructor->getInheritedConstructor().getShadowDecl();
9342*67e74705SXin Li CXXConstructorDecl *InheritedCtor =
9343*67e74705SXin Li Constructor->getInheritedConstructor().getConstructor();
9344*67e74705SXin Li
9345*67e74705SXin Li // [class.inhctor.init]p1:
9346*67e74705SXin Li // initialization proceeds as if a defaulted default constructor is used to
9347*67e74705SXin Li // initialize the D object and each base class subobject from which the
9348*67e74705SXin Li // constructor was inherited
9349*67e74705SXin Li
9350*67e74705SXin Li InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
9351*67e74705SXin Li CXXRecordDecl *RD = Shadow->getParent();
9352*67e74705SXin Li SourceLocation InitLoc = Shadow->getLocation();
9353*67e74705SXin Li
9354*67e74705SXin Li // Initializations are performed "as if by a defaulted default constructor",
9355*67e74705SXin Li // so enter the appropriate scope.
9356*67e74705SXin Li SynthesizedFunctionScope Scope(*this, Constructor);
9357*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
9358*67e74705SXin Li
9359*67e74705SXin Li // Build explicit initializers for all base classes from which the
9360*67e74705SXin Li // constructor was inherited.
9361*67e74705SXin Li SmallVector<CXXCtorInitializer*, 8> Inits;
9362*67e74705SXin Li for (bool VBase : {false, true}) {
9363*67e74705SXin Li for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
9364*67e74705SXin Li if (B.isVirtual() != VBase)
9365*67e74705SXin Li continue;
9366*67e74705SXin Li
9367*67e74705SXin Li auto *BaseRD = B.getType()->getAsCXXRecordDecl();
9368*67e74705SXin Li if (!BaseRD)
9369*67e74705SXin Li continue;
9370*67e74705SXin Li
9371*67e74705SXin Li auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
9372*67e74705SXin Li if (!BaseCtor.first)
9373*67e74705SXin Li continue;
9374*67e74705SXin Li
9375*67e74705SXin Li MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
9376*67e74705SXin Li ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
9377*67e74705SXin Li InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
9378*67e74705SXin Li
9379*67e74705SXin Li auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
9380*67e74705SXin Li Inits.push_back(new (Context) CXXCtorInitializer(
9381*67e74705SXin Li Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
9382*67e74705SXin Li SourceLocation()));
9383*67e74705SXin Li }
9384*67e74705SXin Li }
9385*67e74705SXin Li
9386*67e74705SXin Li // We now proceed as if for a defaulted default constructor, with the relevant
9387*67e74705SXin Li // initializers replaced.
9388*67e74705SXin Li
9389*67e74705SXin Li bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
9390*67e74705SXin Li if (HadError || Trap.hasErrorOccurred()) {
9391*67e74705SXin Li Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
9392*67e74705SXin Li Constructor->setInvalidDecl();
9393*67e74705SXin Li return;
9394*67e74705SXin Li }
9395*67e74705SXin Li
9396*67e74705SXin Li // The exception specification is needed because we are defining the
9397*67e74705SXin Li // function.
9398*67e74705SXin Li ResolveExceptionSpec(CurrentLocation,
9399*67e74705SXin Li Constructor->getType()->castAs<FunctionProtoType>());
9400*67e74705SXin Li
9401*67e74705SXin Li Constructor->setBody(new (Context) CompoundStmt(InitLoc));
9402*67e74705SXin Li
9403*67e74705SXin Li Constructor->markUsed(Context);
9404*67e74705SXin Li MarkVTableUsed(CurrentLocation, ClassDecl);
9405*67e74705SXin Li
9406*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
9407*67e74705SXin Li L->CompletedImplicitDefinition(Constructor);
9408*67e74705SXin Li }
9409*67e74705SXin Li
9410*67e74705SXin Li DiagnoseUninitializedFields(*this, Constructor);
9411*67e74705SXin Li }
9412*67e74705SXin Li
9413*67e74705SXin Li Sema::ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl * MD)9414*67e74705SXin Li Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9415*67e74705SXin Li CXXRecordDecl *ClassDecl = MD->getParent();
9416*67e74705SXin Li
9417*67e74705SXin Li // C++ [except.spec]p14:
9418*67e74705SXin Li // An implicitly declared special member function (Clause 12) shall have
9419*67e74705SXin Li // an exception-specification.
9420*67e74705SXin Li ImplicitExceptionSpecification ExceptSpec(*this);
9421*67e74705SXin Li if (ClassDecl->isInvalidDecl())
9422*67e74705SXin Li return ExceptSpec;
9423*67e74705SXin Li
9424*67e74705SXin Li // Direct base-class destructors.
9425*67e74705SXin Li for (const auto &B : ClassDecl->bases()) {
9426*67e74705SXin Li if (B.isVirtual()) // Handled below.
9427*67e74705SXin Li continue;
9428*67e74705SXin Li
9429*67e74705SXin Li if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9430*67e74705SXin Li ExceptSpec.CalledDecl(B.getLocStart(),
9431*67e74705SXin Li LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9432*67e74705SXin Li }
9433*67e74705SXin Li
9434*67e74705SXin Li // Virtual base-class destructors.
9435*67e74705SXin Li for (const auto &B : ClassDecl->vbases()) {
9436*67e74705SXin Li if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9437*67e74705SXin Li ExceptSpec.CalledDecl(B.getLocStart(),
9438*67e74705SXin Li LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9439*67e74705SXin Li }
9440*67e74705SXin Li
9441*67e74705SXin Li // Field destructors.
9442*67e74705SXin Li for (const auto *F : ClassDecl->fields()) {
9443*67e74705SXin Li if (const RecordType *RecordTy
9444*67e74705SXin Li = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9445*67e74705SXin Li ExceptSpec.CalledDecl(F->getLocation(),
9446*67e74705SXin Li LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9447*67e74705SXin Li }
9448*67e74705SXin Li
9449*67e74705SXin Li return ExceptSpec;
9450*67e74705SXin Li }
9451*67e74705SXin Li
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)9452*67e74705SXin Li CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9453*67e74705SXin Li // C++ [class.dtor]p2:
9454*67e74705SXin Li // If a class has no user-declared destructor, a destructor is
9455*67e74705SXin Li // declared implicitly. An implicitly-declared destructor is an
9456*67e74705SXin Li // inline public member of its class.
9457*67e74705SXin Li assert(ClassDecl->needsImplicitDestructor());
9458*67e74705SXin Li
9459*67e74705SXin Li DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9460*67e74705SXin Li if (DSM.isAlreadyBeingDeclared())
9461*67e74705SXin Li return nullptr;
9462*67e74705SXin Li
9463*67e74705SXin Li // Create the actual destructor declaration.
9464*67e74705SXin Li CanQualType ClassType
9465*67e74705SXin Li = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9466*67e74705SXin Li SourceLocation ClassLoc = ClassDecl->getLocation();
9467*67e74705SXin Li DeclarationName Name
9468*67e74705SXin Li = Context.DeclarationNames.getCXXDestructorName(ClassType);
9469*67e74705SXin Li DeclarationNameInfo NameInfo(Name, ClassLoc);
9470*67e74705SXin Li CXXDestructorDecl *Destructor
9471*67e74705SXin Li = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9472*67e74705SXin Li QualType(), nullptr, /*isInline=*/true,
9473*67e74705SXin Li /*isImplicitlyDeclared=*/true);
9474*67e74705SXin Li Destructor->setAccess(AS_public);
9475*67e74705SXin Li Destructor->setDefaulted();
9476*67e74705SXin Li
9477*67e74705SXin Li if (getLangOpts().CUDA) {
9478*67e74705SXin Li inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9479*67e74705SXin Li Destructor,
9480*67e74705SXin Li /* ConstRHS */ false,
9481*67e74705SXin Li /* Diagnose */ false);
9482*67e74705SXin Li }
9483*67e74705SXin Li
9484*67e74705SXin Li // Build an exception specification pointing back at this destructor.
9485*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9486*67e74705SXin Li Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9487*67e74705SXin Li
9488*67e74705SXin Li // We don't need to use SpecialMemberIsTrivial here; triviality for
9489*67e74705SXin Li // destructors is easy to compute.
9490*67e74705SXin Li Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9491*67e74705SXin Li
9492*67e74705SXin Li // Note that we have declared this destructor.
9493*67e74705SXin Li ++ASTContext::NumImplicitDestructorsDeclared;
9494*67e74705SXin Li
9495*67e74705SXin Li Scope *S = getScopeForContext(ClassDecl);
9496*67e74705SXin Li CheckImplicitSpecialMemberDeclaration(S, Destructor);
9497*67e74705SXin Li
9498*67e74705SXin Li if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9499*67e74705SXin Li SetDeclDeleted(Destructor, ClassLoc);
9500*67e74705SXin Li
9501*67e74705SXin Li // Introduce this destructor into its scope.
9502*67e74705SXin Li if (S)
9503*67e74705SXin Li PushOnScopeChains(Destructor, S, false);
9504*67e74705SXin Li ClassDecl->addDecl(Destructor);
9505*67e74705SXin Li
9506*67e74705SXin Li return Destructor;
9507*67e74705SXin Li }
9508*67e74705SXin Li
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)9509*67e74705SXin Li void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9510*67e74705SXin Li CXXDestructorDecl *Destructor) {
9511*67e74705SXin Li assert((Destructor->isDefaulted() &&
9512*67e74705SXin Li !Destructor->doesThisDeclarationHaveABody() &&
9513*67e74705SXin Li !Destructor->isDeleted()) &&
9514*67e74705SXin Li "DefineImplicitDestructor - call it for implicit default dtor");
9515*67e74705SXin Li CXXRecordDecl *ClassDecl = Destructor->getParent();
9516*67e74705SXin Li assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9517*67e74705SXin Li
9518*67e74705SXin Li if (Destructor->isInvalidDecl())
9519*67e74705SXin Li return;
9520*67e74705SXin Li
9521*67e74705SXin Li SynthesizedFunctionScope Scope(*this, Destructor);
9522*67e74705SXin Li
9523*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
9524*67e74705SXin Li MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9525*67e74705SXin Li Destructor->getParent());
9526*67e74705SXin Li
9527*67e74705SXin Li if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9528*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
9529*67e74705SXin Li << CXXDestructor << Context.getTagDeclType(ClassDecl);
9530*67e74705SXin Li
9531*67e74705SXin Li Destructor->setInvalidDecl();
9532*67e74705SXin Li return;
9533*67e74705SXin Li }
9534*67e74705SXin Li
9535*67e74705SXin Li // The exception specification is needed because we are defining the
9536*67e74705SXin Li // function.
9537*67e74705SXin Li ResolveExceptionSpec(CurrentLocation,
9538*67e74705SXin Li Destructor->getType()->castAs<FunctionProtoType>());
9539*67e74705SXin Li
9540*67e74705SXin Li SourceLocation Loc = Destructor->getLocEnd().isValid()
9541*67e74705SXin Li ? Destructor->getLocEnd()
9542*67e74705SXin Li : Destructor->getLocation();
9543*67e74705SXin Li Destructor->setBody(new (Context) CompoundStmt(Loc));
9544*67e74705SXin Li Destructor->markUsed(Context);
9545*67e74705SXin Li MarkVTableUsed(CurrentLocation, ClassDecl);
9546*67e74705SXin Li
9547*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
9548*67e74705SXin Li L->CompletedImplicitDefinition(Destructor);
9549*67e74705SXin Li }
9550*67e74705SXin Li }
9551*67e74705SXin Li
9552*67e74705SXin Li /// \brief Perform any semantic analysis which needs to be delayed until all
9553*67e74705SXin Li /// pending class member declarations have been parsed.
ActOnFinishCXXMemberDecls()9554*67e74705SXin Li void Sema::ActOnFinishCXXMemberDecls() {
9555*67e74705SXin Li // If the context is an invalid C++ class, just suppress these checks.
9556*67e74705SXin Li if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9557*67e74705SXin Li if (Record->isInvalidDecl()) {
9558*67e74705SXin Li DelayedDefaultedMemberExceptionSpecs.clear();
9559*67e74705SXin Li DelayedExceptionSpecChecks.clear();
9560*67e74705SXin Li return;
9561*67e74705SXin Li }
9562*67e74705SXin Li }
9563*67e74705SXin Li }
9564*67e74705SXin Li
getDefaultArgExprsForConstructors(Sema & S,CXXRecordDecl * Class)9565*67e74705SXin Li static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9566*67e74705SXin Li // Don't do anything for template patterns.
9567*67e74705SXin Li if (Class->getDescribedClassTemplate())
9568*67e74705SXin Li return;
9569*67e74705SXin Li
9570*67e74705SXin Li CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
9571*67e74705SXin Li /*IsVariadic=*/false, /*IsCXXMethod=*/true);
9572*67e74705SXin Li
9573*67e74705SXin Li CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
9574*67e74705SXin Li for (Decl *Member : Class->decls()) {
9575*67e74705SXin Li auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9576*67e74705SXin Li if (!CD) {
9577*67e74705SXin Li // Recurse on nested classes.
9578*67e74705SXin Li if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9579*67e74705SXin Li getDefaultArgExprsForConstructors(S, NestedRD);
9580*67e74705SXin Li continue;
9581*67e74705SXin Li } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9582*67e74705SXin Li continue;
9583*67e74705SXin Li }
9584*67e74705SXin Li
9585*67e74705SXin Li CallingConv ActualCallingConv =
9586*67e74705SXin Li CD->getType()->getAs<FunctionProtoType>()->getCallConv();
9587*67e74705SXin Li
9588*67e74705SXin Li // Skip default constructors with typical calling conventions and no default
9589*67e74705SXin Li // arguments.
9590*67e74705SXin Li unsigned NumParams = CD->getNumParams();
9591*67e74705SXin Li if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
9592*67e74705SXin Li continue;
9593*67e74705SXin Li
9594*67e74705SXin Li if (LastExportedDefaultCtor) {
9595*67e74705SXin Li S.Diag(LastExportedDefaultCtor->getLocation(),
9596*67e74705SXin Li diag::err_attribute_dll_ambiguous_default_ctor) << Class;
9597*67e74705SXin Li S.Diag(CD->getLocation(), diag::note_entity_declared_at)
9598*67e74705SXin Li << CD->getDeclName();
9599*67e74705SXin Li return;
9600*67e74705SXin Li }
9601*67e74705SXin Li LastExportedDefaultCtor = CD;
9602*67e74705SXin Li
9603*67e74705SXin Li for (unsigned I = 0; I != NumParams; ++I) {
9604*67e74705SXin Li // Skip any default arguments that we've already instantiated.
9605*67e74705SXin Li if (S.Context.getDefaultArgExprForConstructor(CD, I))
9606*67e74705SXin Li continue;
9607*67e74705SXin Li
9608*67e74705SXin Li Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9609*67e74705SXin Li CD->getParamDecl(I)).get();
9610*67e74705SXin Li S.DiscardCleanupsInEvaluationContext();
9611*67e74705SXin Li S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9612*67e74705SXin Li }
9613*67e74705SXin Li }
9614*67e74705SXin Li }
9615*67e74705SXin Li
ActOnFinishCXXNonNestedClass(Decl * D)9616*67e74705SXin Li void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
9617*67e74705SXin Li auto *RD = dyn_cast<CXXRecordDecl>(D);
9618*67e74705SXin Li
9619*67e74705SXin Li // Default constructors that are annotated with __declspec(dllexport) which
9620*67e74705SXin Li // have default arguments or don't use the standard calling convention are
9621*67e74705SXin Li // wrapped with a thunk called the default constructor closure.
9622*67e74705SXin Li if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9623*67e74705SXin Li getDefaultArgExprsForConstructors(*this, RD);
9624*67e74705SXin Li
9625*67e74705SXin Li referenceDLLExportedClassMethods();
9626*67e74705SXin Li }
9627*67e74705SXin Li
referenceDLLExportedClassMethods()9628*67e74705SXin Li void Sema::referenceDLLExportedClassMethods() {
9629*67e74705SXin Li if (!DelayedDllExportClasses.empty()) {
9630*67e74705SXin Li // Calling ReferenceDllExportedMethods might cause the current function to
9631*67e74705SXin Li // be called again, so use a local copy of DelayedDllExportClasses.
9632*67e74705SXin Li SmallVector<CXXRecordDecl *, 4> WorkList;
9633*67e74705SXin Li std::swap(DelayedDllExportClasses, WorkList);
9634*67e74705SXin Li for (CXXRecordDecl *Class : WorkList)
9635*67e74705SXin Li ReferenceDllExportedMethods(*this, Class);
9636*67e74705SXin Li }
9637*67e74705SXin Li }
9638*67e74705SXin Li
AdjustDestructorExceptionSpec(CXXRecordDecl * ClassDecl,CXXDestructorDecl * Destructor)9639*67e74705SXin Li void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9640*67e74705SXin Li CXXDestructorDecl *Destructor) {
9641*67e74705SXin Li assert(getLangOpts().CPlusPlus11 &&
9642*67e74705SXin Li "adjusting dtor exception specs was introduced in c++11");
9643*67e74705SXin Li
9644*67e74705SXin Li // C++11 [class.dtor]p3:
9645*67e74705SXin Li // A declaration of a destructor that does not have an exception-
9646*67e74705SXin Li // specification is implicitly considered to have the same exception-
9647*67e74705SXin Li // specification as an implicit declaration.
9648*67e74705SXin Li const FunctionProtoType *DtorType = Destructor->getType()->
9649*67e74705SXin Li getAs<FunctionProtoType>();
9650*67e74705SXin Li if (DtorType->hasExceptionSpec())
9651*67e74705SXin Li return;
9652*67e74705SXin Li
9653*67e74705SXin Li // Replace the destructor's type, building off the existing one. Fortunately,
9654*67e74705SXin Li // the only thing of interest in the destructor type is its extended info.
9655*67e74705SXin Li // The return and arguments are fixed.
9656*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9657*67e74705SXin Li EPI.ExceptionSpec.Type = EST_Unevaluated;
9658*67e74705SXin Li EPI.ExceptionSpec.SourceDecl = Destructor;
9659*67e74705SXin Li Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9660*67e74705SXin Li
9661*67e74705SXin Li // FIXME: If the destructor has a body that could throw, and the newly created
9662*67e74705SXin Li // spec doesn't allow exceptions, we should emit a warning, because this
9663*67e74705SXin Li // change in behavior can break conforming C++03 programs at runtime.
9664*67e74705SXin Li // However, we don't have a body or an exception specification yet, so it
9665*67e74705SXin Li // needs to be done somewhere else.
9666*67e74705SXin Li }
9667*67e74705SXin Li
9668*67e74705SXin Li namespace {
9669*67e74705SXin Li /// \brief An abstract base class for all helper classes used in building the
9670*67e74705SXin Li // copy/move operators. These classes serve as factory functions and help us
9671*67e74705SXin Li // avoid using the same Expr* in the AST twice.
9672*67e74705SXin Li class ExprBuilder {
9673*67e74705SXin Li ExprBuilder(const ExprBuilder&) = delete;
9674*67e74705SXin Li ExprBuilder &operator=(const ExprBuilder&) = delete;
9675*67e74705SXin Li
9676*67e74705SXin Li protected:
assertNotNull(Expr * E)9677*67e74705SXin Li static Expr *assertNotNull(Expr *E) {
9678*67e74705SXin Li assert(E && "Expression construction must not fail.");
9679*67e74705SXin Li return E;
9680*67e74705SXin Li }
9681*67e74705SXin Li
9682*67e74705SXin Li public:
ExprBuilder()9683*67e74705SXin Li ExprBuilder() {}
~ExprBuilder()9684*67e74705SXin Li virtual ~ExprBuilder() {}
9685*67e74705SXin Li
9686*67e74705SXin Li virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9687*67e74705SXin Li };
9688*67e74705SXin Li
9689*67e74705SXin Li class RefBuilder: public ExprBuilder {
9690*67e74705SXin Li VarDecl *Var;
9691*67e74705SXin Li QualType VarType;
9692*67e74705SXin Li
9693*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9694*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9695*67e74705SXin Li return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9696*67e74705SXin Li }
9697*67e74705SXin Li
RefBuilder(VarDecl * Var,QualType VarType)9698*67e74705SXin Li RefBuilder(VarDecl *Var, QualType VarType)
9699*67e74705SXin Li : Var(Var), VarType(VarType) {}
9700*67e74705SXin Li };
9701*67e74705SXin Li
9702*67e74705SXin Li class ThisBuilder: public ExprBuilder {
9703*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9704*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9705*67e74705SXin Li return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9706*67e74705SXin Li }
9707*67e74705SXin Li };
9708*67e74705SXin Li
9709*67e74705SXin Li class CastBuilder: public ExprBuilder {
9710*67e74705SXin Li const ExprBuilder &Builder;
9711*67e74705SXin Li QualType Type;
9712*67e74705SXin Li ExprValueKind Kind;
9713*67e74705SXin Li const CXXCastPath &Path;
9714*67e74705SXin Li
9715*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9716*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9717*67e74705SXin Li return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9718*67e74705SXin Li CK_UncheckedDerivedToBase, Kind,
9719*67e74705SXin Li &Path).get());
9720*67e74705SXin Li }
9721*67e74705SXin Li
CastBuilder(const ExprBuilder & Builder,QualType Type,ExprValueKind Kind,const CXXCastPath & Path)9722*67e74705SXin Li CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9723*67e74705SXin Li const CXXCastPath &Path)
9724*67e74705SXin Li : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9725*67e74705SXin Li };
9726*67e74705SXin Li
9727*67e74705SXin Li class DerefBuilder: public ExprBuilder {
9728*67e74705SXin Li const ExprBuilder &Builder;
9729*67e74705SXin Li
9730*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9731*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9732*67e74705SXin Li return assertNotNull(
9733*67e74705SXin Li S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9734*67e74705SXin Li }
9735*67e74705SXin Li
DerefBuilder(const ExprBuilder & Builder)9736*67e74705SXin Li DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9737*67e74705SXin Li };
9738*67e74705SXin Li
9739*67e74705SXin Li class MemberBuilder: public ExprBuilder {
9740*67e74705SXin Li const ExprBuilder &Builder;
9741*67e74705SXin Li QualType Type;
9742*67e74705SXin Li CXXScopeSpec SS;
9743*67e74705SXin Li bool IsArrow;
9744*67e74705SXin Li LookupResult &MemberLookup;
9745*67e74705SXin Li
9746*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9747*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9748*67e74705SXin Li return assertNotNull(S.BuildMemberReferenceExpr(
9749*67e74705SXin Li Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9750*67e74705SXin Li nullptr, MemberLookup, nullptr, nullptr).get());
9751*67e74705SXin Li }
9752*67e74705SXin Li
MemberBuilder(const ExprBuilder & Builder,QualType Type,bool IsArrow,LookupResult & MemberLookup)9753*67e74705SXin Li MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9754*67e74705SXin Li LookupResult &MemberLookup)
9755*67e74705SXin Li : Builder(Builder), Type(Type), IsArrow(IsArrow),
9756*67e74705SXin Li MemberLookup(MemberLookup) {}
9757*67e74705SXin Li };
9758*67e74705SXin Li
9759*67e74705SXin Li class MoveCastBuilder: public ExprBuilder {
9760*67e74705SXin Li const ExprBuilder &Builder;
9761*67e74705SXin Li
9762*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9763*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9764*67e74705SXin Li return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9765*67e74705SXin Li }
9766*67e74705SXin Li
MoveCastBuilder(const ExprBuilder & Builder)9767*67e74705SXin Li MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9768*67e74705SXin Li };
9769*67e74705SXin Li
9770*67e74705SXin Li class LvalueConvBuilder: public ExprBuilder {
9771*67e74705SXin Li const ExprBuilder &Builder;
9772*67e74705SXin Li
9773*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9774*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9775*67e74705SXin Li return assertNotNull(
9776*67e74705SXin Li S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9777*67e74705SXin Li }
9778*67e74705SXin Li
LvalueConvBuilder(const ExprBuilder & Builder)9779*67e74705SXin Li LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9780*67e74705SXin Li };
9781*67e74705SXin Li
9782*67e74705SXin Li class SubscriptBuilder: public ExprBuilder {
9783*67e74705SXin Li const ExprBuilder &Base;
9784*67e74705SXin Li const ExprBuilder &Index;
9785*67e74705SXin Li
9786*67e74705SXin Li public:
build(Sema & S,SourceLocation Loc) const9787*67e74705SXin Li Expr *build(Sema &S, SourceLocation Loc) const override {
9788*67e74705SXin Li return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9789*67e74705SXin Li Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9790*67e74705SXin Li }
9791*67e74705SXin Li
SubscriptBuilder(const ExprBuilder & Base,const ExprBuilder & Index)9792*67e74705SXin Li SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9793*67e74705SXin Li : Base(Base), Index(Index) {}
9794*67e74705SXin Li };
9795*67e74705SXin Li
9796*67e74705SXin Li } // end anonymous namespace
9797*67e74705SXin Li
9798*67e74705SXin Li /// When generating a defaulted copy or move assignment operator, if a field
9799*67e74705SXin Li /// should be copied with __builtin_memcpy rather than via explicit assignments,
9800*67e74705SXin Li /// do so. This optimization only applies for arrays of scalars, and for arrays
9801*67e74705SXin Li /// of class type where the selected copy/move-assignment operator is trivial.
9802*67e74705SXin Li static StmtResult
buildMemcpyForAssignmentOp(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & ToB,const ExprBuilder & FromB)9803*67e74705SXin Li buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9804*67e74705SXin Li const ExprBuilder &ToB, const ExprBuilder &FromB) {
9805*67e74705SXin Li // Compute the size of the memory buffer to be copied.
9806*67e74705SXin Li QualType SizeType = S.Context.getSizeType();
9807*67e74705SXin Li llvm::APInt Size(S.Context.getTypeSize(SizeType),
9808*67e74705SXin Li S.Context.getTypeSizeInChars(T).getQuantity());
9809*67e74705SXin Li
9810*67e74705SXin Li // Take the address of the field references for "from" and "to". We
9811*67e74705SXin Li // directly construct UnaryOperators here because semantic analysis
9812*67e74705SXin Li // does not permit us to take the address of an xvalue.
9813*67e74705SXin Li Expr *From = FromB.build(S, Loc);
9814*67e74705SXin Li From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9815*67e74705SXin Li S.Context.getPointerType(From->getType()),
9816*67e74705SXin Li VK_RValue, OK_Ordinary, Loc);
9817*67e74705SXin Li Expr *To = ToB.build(S, Loc);
9818*67e74705SXin Li To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9819*67e74705SXin Li S.Context.getPointerType(To->getType()),
9820*67e74705SXin Li VK_RValue, OK_Ordinary, Loc);
9821*67e74705SXin Li
9822*67e74705SXin Li const Type *E = T->getBaseElementTypeUnsafe();
9823*67e74705SXin Li bool NeedsCollectableMemCpy =
9824*67e74705SXin Li E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9825*67e74705SXin Li
9826*67e74705SXin Li // Create a reference to the __builtin_objc_memmove_collectable function
9827*67e74705SXin Li StringRef MemCpyName = NeedsCollectableMemCpy ?
9828*67e74705SXin Li "__builtin_objc_memmove_collectable" :
9829*67e74705SXin Li "__builtin_memcpy";
9830*67e74705SXin Li LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9831*67e74705SXin Li Sema::LookupOrdinaryName);
9832*67e74705SXin Li S.LookupName(R, S.TUScope, true);
9833*67e74705SXin Li
9834*67e74705SXin Li FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9835*67e74705SXin Li if (!MemCpy)
9836*67e74705SXin Li // Something went horribly wrong earlier, and we will have complained
9837*67e74705SXin Li // about it.
9838*67e74705SXin Li return StmtError();
9839*67e74705SXin Li
9840*67e74705SXin Li ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9841*67e74705SXin Li VK_RValue, Loc, nullptr);
9842*67e74705SXin Li assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9843*67e74705SXin Li
9844*67e74705SXin Li Expr *CallArgs[] = {
9845*67e74705SXin Li To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9846*67e74705SXin Li };
9847*67e74705SXin Li ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9848*67e74705SXin Li Loc, CallArgs, Loc);
9849*67e74705SXin Li
9850*67e74705SXin Li assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9851*67e74705SXin Li return Call.getAs<Stmt>();
9852*67e74705SXin Li }
9853*67e74705SXin Li
9854*67e74705SXin Li /// \brief Builds a statement that copies/moves the given entity from \p From to
9855*67e74705SXin Li /// \c To.
9856*67e74705SXin Li ///
9857*67e74705SXin Li /// This routine is used to copy/move the members of a class with an
9858*67e74705SXin Li /// implicitly-declared copy/move assignment operator. When the entities being
9859*67e74705SXin Li /// copied are arrays, this routine builds for loops to copy them.
9860*67e74705SXin Li ///
9861*67e74705SXin Li /// \param S The Sema object used for type-checking.
9862*67e74705SXin Li ///
9863*67e74705SXin Li /// \param Loc The location where the implicit copy/move is being generated.
9864*67e74705SXin Li ///
9865*67e74705SXin Li /// \param T The type of the expressions being copied/moved. Both expressions
9866*67e74705SXin Li /// must have this type.
9867*67e74705SXin Li ///
9868*67e74705SXin Li /// \param To The expression we are copying/moving to.
9869*67e74705SXin Li ///
9870*67e74705SXin Li /// \param From The expression we are copying/moving from.
9871*67e74705SXin Li ///
9872*67e74705SXin Li /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9873*67e74705SXin Li /// Otherwise, it's a non-static member subobject.
9874*67e74705SXin Li ///
9875*67e74705SXin Li /// \param Copying Whether we're copying or moving.
9876*67e74705SXin Li ///
9877*67e74705SXin Li /// \param Depth Internal parameter recording the depth of the recursion.
9878*67e74705SXin Li ///
9879*67e74705SXin Li /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9880*67e74705SXin Li /// if a memcpy should be used instead.
9881*67e74705SXin Li static StmtResult
buildSingleCopyAssignRecursively(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying,unsigned Depth=0)9882*67e74705SXin Li buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9883*67e74705SXin Li const ExprBuilder &To, const ExprBuilder &From,
9884*67e74705SXin Li bool CopyingBaseSubobject, bool Copying,
9885*67e74705SXin Li unsigned Depth = 0) {
9886*67e74705SXin Li // C++11 [class.copy]p28:
9887*67e74705SXin Li // Each subobject is assigned in the manner appropriate to its type:
9888*67e74705SXin Li //
9889*67e74705SXin Li // - if the subobject is of class type, as if by a call to operator= with
9890*67e74705SXin Li // the subobject as the object expression and the corresponding
9891*67e74705SXin Li // subobject of x as a single function argument (as if by explicit
9892*67e74705SXin Li // qualification; that is, ignoring any possible virtual overriding
9893*67e74705SXin Li // functions in more derived classes);
9894*67e74705SXin Li //
9895*67e74705SXin Li // C++03 [class.copy]p13:
9896*67e74705SXin Li // - if the subobject is of class type, the copy assignment operator for
9897*67e74705SXin Li // the class is used (as if by explicit qualification; that is,
9898*67e74705SXin Li // ignoring any possible virtual overriding functions in more derived
9899*67e74705SXin Li // classes);
9900*67e74705SXin Li if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9901*67e74705SXin Li CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9902*67e74705SXin Li
9903*67e74705SXin Li // Look for operator=.
9904*67e74705SXin Li DeclarationName Name
9905*67e74705SXin Li = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9906*67e74705SXin Li LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9907*67e74705SXin Li S.LookupQualifiedName(OpLookup, ClassDecl, false);
9908*67e74705SXin Li
9909*67e74705SXin Li // Prior to C++11, filter out any result that isn't a copy/move-assignment
9910*67e74705SXin Li // operator.
9911*67e74705SXin Li if (!S.getLangOpts().CPlusPlus11) {
9912*67e74705SXin Li LookupResult::Filter F = OpLookup.makeFilter();
9913*67e74705SXin Li while (F.hasNext()) {
9914*67e74705SXin Li NamedDecl *D = F.next();
9915*67e74705SXin Li if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9916*67e74705SXin Li if (Method->isCopyAssignmentOperator() ||
9917*67e74705SXin Li (!Copying && Method->isMoveAssignmentOperator()))
9918*67e74705SXin Li continue;
9919*67e74705SXin Li
9920*67e74705SXin Li F.erase();
9921*67e74705SXin Li }
9922*67e74705SXin Li F.done();
9923*67e74705SXin Li }
9924*67e74705SXin Li
9925*67e74705SXin Li // Suppress the protected check (C++ [class.protected]) for each of the
9926*67e74705SXin Li // assignment operators we found. This strange dance is required when
9927*67e74705SXin Li // we're assigning via a base classes's copy-assignment operator. To
9928*67e74705SXin Li // ensure that we're getting the right base class subobject (without
9929*67e74705SXin Li // ambiguities), we need to cast "this" to that subobject type; to
9930*67e74705SXin Li // ensure that we don't go through the virtual call mechanism, we need
9931*67e74705SXin Li // to qualify the operator= name with the base class (see below). However,
9932*67e74705SXin Li // this means that if the base class has a protected copy assignment
9933*67e74705SXin Li // operator, the protected member access check will fail. So, we
9934*67e74705SXin Li // rewrite "protected" access to "public" access in this case, since we
9935*67e74705SXin Li // know by construction that we're calling from a derived class.
9936*67e74705SXin Li if (CopyingBaseSubobject) {
9937*67e74705SXin Li for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9938*67e74705SXin Li L != LEnd; ++L) {
9939*67e74705SXin Li if (L.getAccess() == AS_protected)
9940*67e74705SXin Li L.setAccess(AS_public);
9941*67e74705SXin Li }
9942*67e74705SXin Li }
9943*67e74705SXin Li
9944*67e74705SXin Li // Create the nested-name-specifier that will be used to qualify the
9945*67e74705SXin Li // reference to operator=; this is required to suppress the virtual
9946*67e74705SXin Li // call mechanism.
9947*67e74705SXin Li CXXScopeSpec SS;
9948*67e74705SXin Li const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9949*67e74705SXin Li SS.MakeTrivial(S.Context,
9950*67e74705SXin Li NestedNameSpecifier::Create(S.Context, nullptr, false,
9951*67e74705SXin Li CanonicalT),
9952*67e74705SXin Li Loc);
9953*67e74705SXin Li
9954*67e74705SXin Li // Create the reference to operator=.
9955*67e74705SXin Li ExprResult OpEqualRef
9956*67e74705SXin Li = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9957*67e74705SXin Li SS, /*TemplateKWLoc=*/SourceLocation(),
9958*67e74705SXin Li /*FirstQualifierInScope=*/nullptr,
9959*67e74705SXin Li OpLookup,
9960*67e74705SXin Li /*TemplateArgs=*/nullptr, /*S*/nullptr,
9961*67e74705SXin Li /*SuppressQualifierCheck=*/true);
9962*67e74705SXin Li if (OpEqualRef.isInvalid())
9963*67e74705SXin Li return StmtError();
9964*67e74705SXin Li
9965*67e74705SXin Li // Build the call to the assignment operator.
9966*67e74705SXin Li
9967*67e74705SXin Li Expr *FromInst = From.build(S, Loc);
9968*67e74705SXin Li ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9969*67e74705SXin Li OpEqualRef.getAs<Expr>(),
9970*67e74705SXin Li Loc, FromInst, Loc);
9971*67e74705SXin Li if (Call.isInvalid())
9972*67e74705SXin Li return StmtError();
9973*67e74705SXin Li
9974*67e74705SXin Li // If we built a call to a trivial 'operator=' while copying an array,
9975*67e74705SXin Li // bail out. We'll replace the whole shebang with a memcpy.
9976*67e74705SXin Li CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9977*67e74705SXin Li if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9978*67e74705SXin Li return StmtResult((Stmt*)nullptr);
9979*67e74705SXin Li
9980*67e74705SXin Li // Convert to an expression-statement, and clean up any produced
9981*67e74705SXin Li // temporaries.
9982*67e74705SXin Li return S.ActOnExprStmt(Call);
9983*67e74705SXin Li }
9984*67e74705SXin Li
9985*67e74705SXin Li // - if the subobject is of scalar type, the built-in assignment
9986*67e74705SXin Li // operator is used.
9987*67e74705SXin Li const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9988*67e74705SXin Li if (!ArrayTy) {
9989*67e74705SXin Li ExprResult Assignment = S.CreateBuiltinBinOp(
9990*67e74705SXin Li Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9991*67e74705SXin Li if (Assignment.isInvalid())
9992*67e74705SXin Li return StmtError();
9993*67e74705SXin Li return S.ActOnExprStmt(Assignment);
9994*67e74705SXin Li }
9995*67e74705SXin Li
9996*67e74705SXin Li // - if the subobject is an array, each element is assigned, in the
9997*67e74705SXin Li // manner appropriate to the element type;
9998*67e74705SXin Li
9999*67e74705SXin Li // Construct a loop over the array bounds, e.g.,
10000*67e74705SXin Li //
10001*67e74705SXin Li // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10002*67e74705SXin Li //
10003*67e74705SXin Li // that will copy each of the array elements.
10004*67e74705SXin Li QualType SizeType = S.Context.getSizeType();
10005*67e74705SXin Li
10006*67e74705SXin Li // Create the iteration variable.
10007*67e74705SXin Li IdentifierInfo *IterationVarName = nullptr;
10008*67e74705SXin Li {
10009*67e74705SXin Li SmallString<8> Str;
10010*67e74705SXin Li llvm::raw_svector_ostream OS(Str);
10011*67e74705SXin Li OS << "__i" << Depth;
10012*67e74705SXin Li IterationVarName = &S.Context.Idents.get(OS.str());
10013*67e74705SXin Li }
10014*67e74705SXin Li VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10015*67e74705SXin Li IterationVarName, SizeType,
10016*67e74705SXin Li S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10017*67e74705SXin Li SC_None);
10018*67e74705SXin Li
10019*67e74705SXin Li // Initialize the iteration variable to zero.
10020*67e74705SXin Li llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
10021*67e74705SXin Li IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10022*67e74705SXin Li
10023*67e74705SXin Li // Creates a reference to the iteration variable.
10024*67e74705SXin Li RefBuilder IterationVarRef(IterationVar, SizeType);
10025*67e74705SXin Li LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10026*67e74705SXin Li
10027*67e74705SXin Li // Create the DeclStmt that holds the iteration variable.
10028*67e74705SXin Li Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10029*67e74705SXin Li
10030*67e74705SXin Li // Subscript the "from" and "to" expressions with the iteration variable.
10031*67e74705SXin Li SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10032*67e74705SXin Li MoveCastBuilder FromIndexMove(FromIndexCopy);
10033*67e74705SXin Li const ExprBuilder *FromIndex;
10034*67e74705SXin Li if (Copying)
10035*67e74705SXin Li FromIndex = &FromIndexCopy;
10036*67e74705SXin Li else
10037*67e74705SXin Li FromIndex = &FromIndexMove;
10038*67e74705SXin Li
10039*67e74705SXin Li SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10040*67e74705SXin Li
10041*67e74705SXin Li // Build the copy/move for an individual element of the array.
10042*67e74705SXin Li StmtResult Copy =
10043*67e74705SXin Li buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
10044*67e74705SXin Li ToIndex, *FromIndex, CopyingBaseSubobject,
10045*67e74705SXin Li Copying, Depth + 1);
10046*67e74705SXin Li // Bail out if copying fails or if we determined that we should use memcpy.
10047*67e74705SXin Li if (Copy.isInvalid() || !Copy.get())
10048*67e74705SXin Li return Copy;
10049*67e74705SXin Li
10050*67e74705SXin Li // Create the comparison against the array bound.
10051*67e74705SXin Li llvm::APInt Upper
10052*67e74705SXin Li = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10053*67e74705SXin Li Expr *Comparison
10054*67e74705SXin Li = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10055*67e74705SXin Li IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10056*67e74705SXin Li BO_NE, S.Context.BoolTy,
10057*67e74705SXin Li VK_RValue, OK_Ordinary, Loc, false);
10058*67e74705SXin Li
10059*67e74705SXin Li // Create the pre-increment of the iteration variable.
10060*67e74705SXin Li Expr *Increment
10061*67e74705SXin Li = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10062*67e74705SXin Li SizeType, VK_LValue, OK_Ordinary, Loc);
10063*67e74705SXin Li
10064*67e74705SXin Li // Construct the loop that copies all elements of this array.
10065*67e74705SXin Li return S.ActOnForStmt(
10066*67e74705SXin Li Loc, Loc, InitStmt,
10067*67e74705SXin Li S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10068*67e74705SXin Li S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
10069*67e74705SXin Li }
10070*67e74705SXin Li
10071*67e74705SXin Li static StmtResult
buildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,const ExprBuilder & To,const ExprBuilder & From,bool CopyingBaseSubobject,bool Copying)10072*67e74705SXin Li buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
10073*67e74705SXin Li const ExprBuilder &To, const ExprBuilder &From,
10074*67e74705SXin Li bool CopyingBaseSubobject, bool Copying) {
10075*67e74705SXin Li // Maybe we should use a memcpy?
10076*67e74705SXin Li if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10077*67e74705SXin Li T.isTriviallyCopyableType(S.Context))
10078*67e74705SXin Li return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10079*67e74705SXin Li
10080*67e74705SXin Li StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10081*67e74705SXin Li CopyingBaseSubobject,
10082*67e74705SXin Li Copying, 0));
10083*67e74705SXin Li
10084*67e74705SXin Li // If we ended up picking a trivial assignment operator for an array of a
10085*67e74705SXin Li // non-trivially-copyable class type, just emit a memcpy.
10086*67e74705SXin Li if (!Result.isInvalid() && !Result.get())
10087*67e74705SXin Li return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10088*67e74705SXin Li
10089*67e74705SXin Li return Result;
10090*67e74705SXin Li }
10091*67e74705SXin Li
10092*67e74705SXin Li Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl * MD)10093*67e74705SXin Li Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10094*67e74705SXin Li CXXRecordDecl *ClassDecl = MD->getParent();
10095*67e74705SXin Li
10096*67e74705SXin Li ImplicitExceptionSpecification ExceptSpec(*this);
10097*67e74705SXin Li if (ClassDecl->isInvalidDecl())
10098*67e74705SXin Li return ExceptSpec;
10099*67e74705SXin Li
10100*67e74705SXin Li const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10101*67e74705SXin Li assert(T->getNumParams() == 1 && "not a copy assignment op");
10102*67e74705SXin Li unsigned ArgQuals =
10103*67e74705SXin Li T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10104*67e74705SXin Li
10105*67e74705SXin Li // C++ [except.spec]p14:
10106*67e74705SXin Li // An implicitly declared special member function (Clause 12) shall have an
10107*67e74705SXin Li // exception-specification. [...]
10108*67e74705SXin Li
10109*67e74705SXin Li // It is unspecified whether or not an implicit copy assignment operator
10110*67e74705SXin Li // attempts to deduplicate calls to assignment operators of virtual bases are
10111*67e74705SXin Li // made. As such, this exception specification is effectively unspecified.
10112*67e74705SXin Li // Based on a similar decision made for constness in C++0x, we're erring on
10113*67e74705SXin Li // the side of assuming such calls to be made regardless of whether they
10114*67e74705SXin Li // actually happen.
10115*67e74705SXin Li for (const auto &Base : ClassDecl->bases()) {
10116*67e74705SXin Li if (Base.isVirtual())
10117*67e74705SXin Li continue;
10118*67e74705SXin Li
10119*67e74705SXin Li CXXRecordDecl *BaseClassDecl
10120*67e74705SXin Li = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10121*67e74705SXin Li if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10122*67e74705SXin Li ArgQuals, false, 0))
10123*67e74705SXin Li ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10124*67e74705SXin Li }
10125*67e74705SXin Li
10126*67e74705SXin Li for (const auto &Base : ClassDecl->vbases()) {
10127*67e74705SXin Li CXXRecordDecl *BaseClassDecl
10128*67e74705SXin Li = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10129*67e74705SXin Li if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10130*67e74705SXin Li ArgQuals, false, 0))
10131*67e74705SXin Li ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10132*67e74705SXin Li }
10133*67e74705SXin Li
10134*67e74705SXin Li for (const auto *Field : ClassDecl->fields()) {
10135*67e74705SXin Li QualType FieldType = Context.getBaseElementType(Field->getType());
10136*67e74705SXin Li if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10137*67e74705SXin Li if (CXXMethodDecl *CopyAssign =
10138*67e74705SXin Li LookupCopyingAssignment(FieldClassDecl,
10139*67e74705SXin Li ArgQuals | FieldType.getCVRQualifiers(),
10140*67e74705SXin Li false, 0))
10141*67e74705SXin Li ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10142*67e74705SXin Li }
10143*67e74705SXin Li }
10144*67e74705SXin Li
10145*67e74705SXin Li return ExceptSpec;
10146*67e74705SXin Li }
10147*67e74705SXin Li
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)10148*67e74705SXin Li CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10149*67e74705SXin Li // Note: The following rules are largely analoguous to the copy
10150*67e74705SXin Li // constructor rules. Note that virtual bases are not taken into account
10151*67e74705SXin Li // for determining the argument type of the operator. Note also that
10152*67e74705SXin Li // operators taking an object instead of a reference are allowed.
10153*67e74705SXin Li assert(ClassDecl->needsImplicitCopyAssignment());
10154*67e74705SXin Li
10155*67e74705SXin Li DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10156*67e74705SXin Li if (DSM.isAlreadyBeingDeclared())
10157*67e74705SXin Li return nullptr;
10158*67e74705SXin Li
10159*67e74705SXin Li QualType ArgType = Context.getTypeDeclType(ClassDecl);
10160*67e74705SXin Li QualType RetType = Context.getLValueReferenceType(ArgType);
10161*67e74705SXin Li bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10162*67e74705SXin Li if (Const)
10163*67e74705SXin Li ArgType = ArgType.withConst();
10164*67e74705SXin Li ArgType = Context.getLValueReferenceType(ArgType);
10165*67e74705SXin Li
10166*67e74705SXin Li bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10167*67e74705SXin Li CXXCopyAssignment,
10168*67e74705SXin Li Const);
10169*67e74705SXin Li
10170*67e74705SXin Li // An implicitly-declared copy assignment operator is an inline public
10171*67e74705SXin Li // member of its class.
10172*67e74705SXin Li DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10173*67e74705SXin Li SourceLocation ClassLoc = ClassDecl->getLocation();
10174*67e74705SXin Li DeclarationNameInfo NameInfo(Name, ClassLoc);
10175*67e74705SXin Li CXXMethodDecl *CopyAssignment =
10176*67e74705SXin Li CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10177*67e74705SXin Li /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10178*67e74705SXin Li /*isInline=*/true, Constexpr, SourceLocation());
10179*67e74705SXin Li CopyAssignment->setAccess(AS_public);
10180*67e74705SXin Li CopyAssignment->setDefaulted();
10181*67e74705SXin Li CopyAssignment->setImplicit();
10182*67e74705SXin Li
10183*67e74705SXin Li if (getLangOpts().CUDA) {
10184*67e74705SXin Li inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10185*67e74705SXin Li CopyAssignment,
10186*67e74705SXin Li /* ConstRHS */ Const,
10187*67e74705SXin Li /* Diagnose */ false);
10188*67e74705SXin Li }
10189*67e74705SXin Li
10190*67e74705SXin Li // Build an exception specification pointing back at this member.
10191*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI =
10192*67e74705SXin Li getImplicitMethodEPI(*this, CopyAssignment);
10193*67e74705SXin Li CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10194*67e74705SXin Li
10195*67e74705SXin Li // Add the parameter to the operator.
10196*67e74705SXin Li ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10197*67e74705SXin Li ClassLoc, ClassLoc,
10198*67e74705SXin Li /*Id=*/nullptr, ArgType,
10199*67e74705SXin Li /*TInfo=*/nullptr, SC_None,
10200*67e74705SXin Li nullptr);
10201*67e74705SXin Li CopyAssignment->setParams(FromParam);
10202*67e74705SXin Li
10203*67e74705SXin Li CopyAssignment->setTrivial(
10204*67e74705SXin Li ClassDecl->needsOverloadResolutionForCopyAssignment()
10205*67e74705SXin Li ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10206*67e74705SXin Li : ClassDecl->hasTrivialCopyAssignment());
10207*67e74705SXin Li
10208*67e74705SXin Li // Note that we have added this copy-assignment operator.
10209*67e74705SXin Li ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10210*67e74705SXin Li
10211*67e74705SXin Li Scope *S = getScopeForContext(ClassDecl);
10212*67e74705SXin Li CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10213*67e74705SXin Li
10214*67e74705SXin Li if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10215*67e74705SXin Li SetDeclDeleted(CopyAssignment, ClassLoc);
10216*67e74705SXin Li
10217*67e74705SXin Li if (S)
10218*67e74705SXin Li PushOnScopeChains(CopyAssignment, S, false);
10219*67e74705SXin Li ClassDecl->addDecl(CopyAssignment);
10220*67e74705SXin Li
10221*67e74705SXin Li return CopyAssignment;
10222*67e74705SXin Li }
10223*67e74705SXin Li
10224*67e74705SXin Li /// Diagnose an implicit copy operation for a class which is odr-used, but
10225*67e74705SXin Li /// which is deprecated because the class has a user-declared copy constructor,
10226*67e74705SXin Li /// copy assignment operator, or destructor.
diagnoseDeprecatedCopyOperation(Sema & S,CXXMethodDecl * CopyOp,SourceLocation UseLoc)10227*67e74705SXin Li static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10228*67e74705SXin Li SourceLocation UseLoc) {
10229*67e74705SXin Li assert(CopyOp->isImplicit());
10230*67e74705SXin Li
10231*67e74705SXin Li CXXRecordDecl *RD = CopyOp->getParent();
10232*67e74705SXin Li CXXMethodDecl *UserDeclaredOperation = nullptr;
10233*67e74705SXin Li
10234*67e74705SXin Li // In Microsoft mode, assignment operations don't affect constructors and
10235*67e74705SXin Li // vice versa.
10236*67e74705SXin Li if (RD->hasUserDeclaredDestructor()) {
10237*67e74705SXin Li UserDeclaredOperation = RD->getDestructor();
10238*67e74705SXin Li } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10239*67e74705SXin Li RD->hasUserDeclaredCopyConstructor() &&
10240*67e74705SXin Li !S.getLangOpts().MSVCCompat) {
10241*67e74705SXin Li // Find any user-declared copy constructor.
10242*67e74705SXin Li for (auto *I : RD->ctors()) {
10243*67e74705SXin Li if (I->isCopyConstructor()) {
10244*67e74705SXin Li UserDeclaredOperation = I;
10245*67e74705SXin Li break;
10246*67e74705SXin Li }
10247*67e74705SXin Li }
10248*67e74705SXin Li assert(UserDeclaredOperation);
10249*67e74705SXin Li } else if (isa<CXXConstructorDecl>(CopyOp) &&
10250*67e74705SXin Li RD->hasUserDeclaredCopyAssignment() &&
10251*67e74705SXin Li !S.getLangOpts().MSVCCompat) {
10252*67e74705SXin Li // Find any user-declared move assignment operator.
10253*67e74705SXin Li for (auto *I : RD->methods()) {
10254*67e74705SXin Li if (I->isCopyAssignmentOperator()) {
10255*67e74705SXin Li UserDeclaredOperation = I;
10256*67e74705SXin Li break;
10257*67e74705SXin Li }
10258*67e74705SXin Li }
10259*67e74705SXin Li assert(UserDeclaredOperation);
10260*67e74705SXin Li }
10261*67e74705SXin Li
10262*67e74705SXin Li if (UserDeclaredOperation) {
10263*67e74705SXin Li S.Diag(UserDeclaredOperation->getLocation(),
10264*67e74705SXin Li diag::warn_deprecated_copy_operation)
10265*67e74705SXin Li << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10266*67e74705SXin Li << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10267*67e74705SXin Li S.Diag(UseLoc, diag::note_member_synthesized_at)
10268*67e74705SXin Li << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10269*67e74705SXin Li : Sema::CXXCopyAssignment)
10270*67e74705SXin Li << RD;
10271*67e74705SXin Li }
10272*67e74705SXin Li }
10273*67e74705SXin Li
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)10274*67e74705SXin Li void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10275*67e74705SXin Li CXXMethodDecl *CopyAssignOperator) {
10276*67e74705SXin Li assert((CopyAssignOperator->isDefaulted() &&
10277*67e74705SXin Li CopyAssignOperator->isOverloadedOperator() &&
10278*67e74705SXin Li CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10279*67e74705SXin Li !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10280*67e74705SXin Li !CopyAssignOperator->isDeleted()) &&
10281*67e74705SXin Li "DefineImplicitCopyAssignment called for wrong function");
10282*67e74705SXin Li
10283*67e74705SXin Li CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10284*67e74705SXin Li
10285*67e74705SXin Li if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10286*67e74705SXin Li CopyAssignOperator->setInvalidDecl();
10287*67e74705SXin Li return;
10288*67e74705SXin Li }
10289*67e74705SXin Li
10290*67e74705SXin Li // C++11 [class.copy]p18:
10291*67e74705SXin Li // The [definition of an implicitly declared copy assignment operator] is
10292*67e74705SXin Li // deprecated if the class has a user-declared copy constructor or a
10293*67e74705SXin Li // user-declared destructor.
10294*67e74705SXin Li if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10295*67e74705SXin Li diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10296*67e74705SXin Li
10297*67e74705SXin Li CopyAssignOperator->markUsed(Context);
10298*67e74705SXin Li
10299*67e74705SXin Li SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10300*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
10301*67e74705SXin Li
10302*67e74705SXin Li // C++0x [class.copy]p30:
10303*67e74705SXin Li // The implicitly-defined or explicitly-defaulted copy assignment operator
10304*67e74705SXin Li // for a non-union class X performs memberwise copy assignment of its
10305*67e74705SXin Li // subobjects. The direct base classes of X are assigned first, in the
10306*67e74705SXin Li // order of their declaration in the base-specifier-list, and then the
10307*67e74705SXin Li // immediate non-static data members of X are assigned, in the order in
10308*67e74705SXin Li // which they were declared in the class definition.
10309*67e74705SXin Li
10310*67e74705SXin Li // The statements that form the synthesized function body.
10311*67e74705SXin Li SmallVector<Stmt*, 8> Statements;
10312*67e74705SXin Li
10313*67e74705SXin Li // The parameter for the "other" object, which we are copying from.
10314*67e74705SXin Li ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10315*67e74705SXin Li Qualifiers OtherQuals = Other->getType().getQualifiers();
10316*67e74705SXin Li QualType OtherRefType = Other->getType();
10317*67e74705SXin Li if (const LValueReferenceType *OtherRef
10318*67e74705SXin Li = OtherRefType->getAs<LValueReferenceType>()) {
10319*67e74705SXin Li OtherRefType = OtherRef->getPointeeType();
10320*67e74705SXin Li OtherQuals = OtherRefType.getQualifiers();
10321*67e74705SXin Li }
10322*67e74705SXin Li
10323*67e74705SXin Li // Our location for everything implicitly-generated.
10324*67e74705SXin Li SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10325*67e74705SXin Li ? CopyAssignOperator->getLocEnd()
10326*67e74705SXin Li : CopyAssignOperator->getLocation();
10327*67e74705SXin Li
10328*67e74705SXin Li // Builds a DeclRefExpr for the "other" object.
10329*67e74705SXin Li RefBuilder OtherRef(Other, OtherRefType);
10330*67e74705SXin Li
10331*67e74705SXin Li // Builds the "this" pointer.
10332*67e74705SXin Li ThisBuilder This;
10333*67e74705SXin Li
10334*67e74705SXin Li // Assign base classes.
10335*67e74705SXin Li bool Invalid = false;
10336*67e74705SXin Li for (auto &Base : ClassDecl->bases()) {
10337*67e74705SXin Li // Form the assignment:
10338*67e74705SXin Li // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10339*67e74705SXin Li QualType BaseType = Base.getType().getUnqualifiedType();
10340*67e74705SXin Li if (!BaseType->isRecordType()) {
10341*67e74705SXin Li Invalid = true;
10342*67e74705SXin Li continue;
10343*67e74705SXin Li }
10344*67e74705SXin Li
10345*67e74705SXin Li CXXCastPath BasePath;
10346*67e74705SXin Li BasePath.push_back(&Base);
10347*67e74705SXin Li
10348*67e74705SXin Li // Construct the "from" expression, which is an implicit cast to the
10349*67e74705SXin Li // appropriately-qualified base type.
10350*67e74705SXin Li CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10351*67e74705SXin Li VK_LValue, BasePath);
10352*67e74705SXin Li
10353*67e74705SXin Li // Dereference "this".
10354*67e74705SXin Li DerefBuilder DerefThis(This);
10355*67e74705SXin Li CastBuilder To(DerefThis,
10356*67e74705SXin Li Context.getCVRQualifiedType(
10357*67e74705SXin Li BaseType, CopyAssignOperator->getTypeQualifiers()),
10358*67e74705SXin Li VK_LValue, BasePath);
10359*67e74705SXin Li
10360*67e74705SXin Li // Build the copy.
10361*67e74705SXin Li StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10362*67e74705SXin Li To, From,
10363*67e74705SXin Li /*CopyingBaseSubobject=*/true,
10364*67e74705SXin Li /*Copying=*/true);
10365*67e74705SXin Li if (Copy.isInvalid()) {
10366*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10367*67e74705SXin Li << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10368*67e74705SXin Li CopyAssignOperator->setInvalidDecl();
10369*67e74705SXin Li return;
10370*67e74705SXin Li }
10371*67e74705SXin Li
10372*67e74705SXin Li // Success! Record the copy.
10373*67e74705SXin Li Statements.push_back(Copy.getAs<Expr>());
10374*67e74705SXin Li }
10375*67e74705SXin Li
10376*67e74705SXin Li // Assign non-static members.
10377*67e74705SXin Li for (auto *Field : ClassDecl->fields()) {
10378*67e74705SXin Li // FIXME: We should form some kind of AST representation for the implied
10379*67e74705SXin Li // memcpy in a union copy operation.
10380*67e74705SXin Li if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10381*67e74705SXin Li continue;
10382*67e74705SXin Li
10383*67e74705SXin Li if (Field->isInvalidDecl()) {
10384*67e74705SXin Li Invalid = true;
10385*67e74705SXin Li continue;
10386*67e74705SXin Li }
10387*67e74705SXin Li
10388*67e74705SXin Li // Check for members of reference type; we can't copy those.
10389*67e74705SXin Li if (Field->getType()->isReferenceType()) {
10390*67e74705SXin Li Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10391*67e74705SXin Li << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10392*67e74705SXin Li Diag(Field->getLocation(), diag::note_declared_at);
10393*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10394*67e74705SXin Li << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10395*67e74705SXin Li Invalid = true;
10396*67e74705SXin Li continue;
10397*67e74705SXin Li }
10398*67e74705SXin Li
10399*67e74705SXin Li // Check for members of const-qualified, non-class type.
10400*67e74705SXin Li QualType BaseType = Context.getBaseElementType(Field->getType());
10401*67e74705SXin Li if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10402*67e74705SXin Li Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10403*67e74705SXin Li << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10404*67e74705SXin Li Diag(Field->getLocation(), diag::note_declared_at);
10405*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10406*67e74705SXin Li << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10407*67e74705SXin Li Invalid = true;
10408*67e74705SXin Li continue;
10409*67e74705SXin Li }
10410*67e74705SXin Li
10411*67e74705SXin Li // Suppress assigning zero-width bitfields.
10412*67e74705SXin Li if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10413*67e74705SXin Li continue;
10414*67e74705SXin Li
10415*67e74705SXin Li QualType FieldType = Field->getType().getNonReferenceType();
10416*67e74705SXin Li if (FieldType->isIncompleteArrayType()) {
10417*67e74705SXin Li assert(ClassDecl->hasFlexibleArrayMember() &&
10418*67e74705SXin Li "Incomplete array type is not valid");
10419*67e74705SXin Li continue;
10420*67e74705SXin Li }
10421*67e74705SXin Li
10422*67e74705SXin Li // Build references to the field in the object we're copying from and to.
10423*67e74705SXin Li CXXScopeSpec SS; // Intentionally empty
10424*67e74705SXin Li LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10425*67e74705SXin Li LookupMemberName);
10426*67e74705SXin Li MemberLookup.addDecl(Field);
10427*67e74705SXin Li MemberLookup.resolveKind();
10428*67e74705SXin Li
10429*67e74705SXin Li MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10430*67e74705SXin Li
10431*67e74705SXin Li MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10432*67e74705SXin Li
10433*67e74705SXin Li // Build the copy of this field.
10434*67e74705SXin Li StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10435*67e74705SXin Li To, From,
10436*67e74705SXin Li /*CopyingBaseSubobject=*/false,
10437*67e74705SXin Li /*Copying=*/true);
10438*67e74705SXin Li if (Copy.isInvalid()) {
10439*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10440*67e74705SXin Li << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10441*67e74705SXin Li CopyAssignOperator->setInvalidDecl();
10442*67e74705SXin Li return;
10443*67e74705SXin Li }
10444*67e74705SXin Li
10445*67e74705SXin Li // Success! Record the copy.
10446*67e74705SXin Li Statements.push_back(Copy.getAs<Stmt>());
10447*67e74705SXin Li }
10448*67e74705SXin Li
10449*67e74705SXin Li if (!Invalid) {
10450*67e74705SXin Li // Add a "return *this;"
10451*67e74705SXin Li ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10452*67e74705SXin Li
10453*67e74705SXin Li StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10454*67e74705SXin Li if (Return.isInvalid())
10455*67e74705SXin Li Invalid = true;
10456*67e74705SXin Li else {
10457*67e74705SXin Li Statements.push_back(Return.getAs<Stmt>());
10458*67e74705SXin Li
10459*67e74705SXin Li if (Trap.hasErrorOccurred()) {
10460*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10461*67e74705SXin Li << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10462*67e74705SXin Li Invalid = true;
10463*67e74705SXin Li }
10464*67e74705SXin Li }
10465*67e74705SXin Li }
10466*67e74705SXin Li
10467*67e74705SXin Li // The exception specification is needed because we are defining the
10468*67e74705SXin Li // function.
10469*67e74705SXin Li ResolveExceptionSpec(CurrentLocation,
10470*67e74705SXin Li CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10471*67e74705SXin Li
10472*67e74705SXin Li if (Invalid) {
10473*67e74705SXin Li CopyAssignOperator->setInvalidDecl();
10474*67e74705SXin Li return;
10475*67e74705SXin Li }
10476*67e74705SXin Li
10477*67e74705SXin Li StmtResult Body;
10478*67e74705SXin Li {
10479*67e74705SXin Li CompoundScopeRAII CompoundScope(*this);
10480*67e74705SXin Li Body = ActOnCompoundStmt(Loc, Loc, Statements,
10481*67e74705SXin Li /*isStmtExpr=*/false);
10482*67e74705SXin Li assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10483*67e74705SXin Li }
10484*67e74705SXin Li CopyAssignOperator->setBody(Body.getAs<Stmt>());
10485*67e74705SXin Li
10486*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
10487*67e74705SXin Li L->CompletedImplicitDefinition(CopyAssignOperator);
10488*67e74705SXin Li }
10489*67e74705SXin Li }
10490*67e74705SXin Li
10491*67e74705SXin Li Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl * MD)10492*67e74705SXin Li Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10493*67e74705SXin Li CXXRecordDecl *ClassDecl = MD->getParent();
10494*67e74705SXin Li
10495*67e74705SXin Li ImplicitExceptionSpecification ExceptSpec(*this);
10496*67e74705SXin Li if (ClassDecl->isInvalidDecl())
10497*67e74705SXin Li return ExceptSpec;
10498*67e74705SXin Li
10499*67e74705SXin Li // C++0x [except.spec]p14:
10500*67e74705SXin Li // An implicitly declared special member function (Clause 12) shall have an
10501*67e74705SXin Li // exception-specification. [...]
10502*67e74705SXin Li
10503*67e74705SXin Li // It is unspecified whether or not an implicit move assignment operator
10504*67e74705SXin Li // attempts to deduplicate calls to assignment operators of virtual bases are
10505*67e74705SXin Li // made. As such, this exception specification is effectively unspecified.
10506*67e74705SXin Li // Based on a similar decision made for constness in C++0x, we're erring on
10507*67e74705SXin Li // the side of assuming such calls to be made regardless of whether they
10508*67e74705SXin Li // actually happen.
10509*67e74705SXin Li // Note that a move constructor is not implicitly declared when there are
10510*67e74705SXin Li // virtual bases, but it can still be user-declared and explicitly defaulted.
10511*67e74705SXin Li for (const auto &Base : ClassDecl->bases()) {
10512*67e74705SXin Li if (Base.isVirtual())
10513*67e74705SXin Li continue;
10514*67e74705SXin Li
10515*67e74705SXin Li CXXRecordDecl *BaseClassDecl
10516*67e74705SXin Li = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10517*67e74705SXin Li if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10518*67e74705SXin Li 0, false, 0))
10519*67e74705SXin Li ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10520*67e74705SXin Li }
10521*67e74705SXin Li
10522*67e74705SXin Li for (const auto &Base : ClassDecl->vbases()) {
10523*67e74705SXin Li CXXRecordDecl *BaseClassDecl
10524*67e74705SXin Li = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10525*67e74705SXin Li if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10526*67e74705SXin Li 0, false, 0))
10527*67e74705SXin Li ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10528*67e74705SXin Li }
10529*67e74705SXin Li
10530*67e74705SXin Li for (const auto *Field : ClassDecl->fields()) {
10531*67e74705SXin Li QualType FieldType = Context.getBaseElementType(Field->getType());
10532*67e74705SXin Li if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10533*67e74705SXin Li if (CXXMethodDecl *MoveAssign =
10534*67e74705SXin Li LookupMovingAssignment(FieldClassDecl,
10535*67e74705SXin Li FieldType.getCVRQualifiers(),
10536*67e74705SXin Li false, 0))
10537*67e74705SXin Li ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10538*67e74705SXin Li }
10539*67e74705SXin Li }
10540*67e74705SXin Li
10541*67e74705SXin Li return ExceptSpec;
10542*67e74705SXin Li }
10543*67e74705SXin Li
DeclareImplicitMoveAssignment(CXXRecordDecl * ClassDecl)10544*67e74705SXin Li CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10545*67e74705SXin Li assert(ClassDecl->needsImplicitMoveAssignment());
10546*67e74705SXin Li
10547*67e74705SXin Li DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10548*67e74705SXin Li if (DSM.isAlreadyBeingDeclared())
10549*67e74705SXin Li return nullptr;
10550*67e74705SXin Li
10551*67e74705SXin Li // Note: The following rules are largely analoguous to the move
10552*67e74705SXin Li // constructor rules.
10553*67e74705SXin Li
10554*67e74705SXin Li QualType ArgType = Context.getTypeDeclType(ClassDecl);
10555*67e74705SXin Li QualType RetType = Context.getLValueReferenceType(ArgType);
10556*67e74705SXin Li ArgType = Context.getRValueReferenceType(ArgType);
10557*67e74705SXin Li
10558*67e74705SXin Li bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10559*67e74705SXin Li CXXMoveAssignment,
10560*67e74705SXin Li false);
10561*67e74705SXin Li
10562*67e74705SXin Li // An implicitly-declared move assignment operator is an inline public
10563*67e74705SXin Li // member of its class.
10564*67e74705SXin Li DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10565*67e74705SXin Li SourceLocation ClassLoc = ClassDecl->getLocation();
10566*67e74705SXin Li DeclarationNameInfo NameInfo(Name, ClassLoc);
10567*67e74705SXin Li CXXMethodDecl *MoveAssignment =
10568*67e74705SXin Li CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10569*67e74705SXin Li /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10570*67e74705SXin Li /*isInline=*/true, Constexpr, SourceLocation());
10571*67e74705SXin Li MoveAssignment->setAccess(AS_public);
10572*67e74705SXin Li MoveAssignment->setDefaulted();
10573*67e74705SXin Li MoveAssignment->setImplicit();
10574*67e74705SXin Li
10575*67e74705SXin Li if (getLangOpts().CUDA) {
10576*67e74705SXin Li inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10577*67e74705SXin Li MoveAssignment,
10578*67e74705SXin Li /* ConstRHS */ false,
10579*67e74705SXin Li /* Diagnose */ false);
10580*67e74705SXin Li }
10581*67e74705SXin Li
10582*67e74705SXin Li // Build an exception specification pointing back at this member.
10583*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI =
10584*67e74705SXin Li getImplicitMethodEPI(*this, MoveAssignment);
10585*67e74705SXin Li MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10586*67e74705SXin Li
10587*67e74705SXin Li // Add the parameter to the operator.
10588*67e74705SXin Li ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10589*67e74705SXin Li ClassLoc, ClassLoc,
10590*67e74705SXin Li /*Id=*/nullptr, ArgType,
10591*67e74705SXin Li /*TInfo=*/nullptr, SC_None,
10592*67e74705SXin Li nullptr);
10593*67e74705SXin Li MoveAssignment->setParams(FromParam);
10594*67e74705SXin Li
10595*67e74705SXin Li MoveAssignment->setTrivial(
10596*67e74705SXin Li ClassDecl->needsOverloadResolutionForMoveAssignment()
10597*67e74705SXin Li ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10598*67e74705SXin Li : ClassDecl->hasTrivialMoveAssignment());
10599*67e74705SXin Li
10600*67e74705SXin Li // Note that we have added this copy-assignment operator.
10601*67e74705SXin Li ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10602*67e74705SXin Li
10603*67e74705SXin Li Scope *S = getScopeForContext(ClassDecl);
10604*67e74705SXin Li CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
10605*67e74705SXin Li
10606*67e74705SXin Li if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10607*67e74705SXin Li ClassDecl->setImplicitMoveAssignmentIsDeleted();
10608*67e74705SXin Li SetDeclDeleted(MoveAssignment, ClassLoc);
10609*67e74705SXin Li }
10610*67e74705SXin Li
10611*67e74705SXin Li if (S)
10612*67e74705SXin Li PushOnScopeChains(MoveAssignment, S, false);
10613*67e74705SXin Li ClassDecl->addDecl(MoveAssignment);
10614*67e74705SXin Li
10615*67e74705SXin Li return MoveAssignment;
10616*67e74705SXin Li }
10617*67e74705SXin Li
10618*67e74705SXin Li /// Check if we're implicitly defining a move assignment operator for a class
10619*67e74705SXin Li /// with virtual bases. Such a move assignment might move-assign the virtual
10620*67e74705SXin Li /// base multiple times.
checkMoveAssignmentForRepeatedMove(Sema & S,CXXRecordDecl * Class,SourceLocation CurrentLocation)10621*67e74705SXin Li static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10622*67e74705SXin Li SourceLocation CurrentLocation) {
10623*67e74705SXin Li assert(!Class->isDependentContext() && "should not define dependent move");
10624*67e74705SXin Li
10625*67e74705SXin Li // Only a virtual base could get implicitly move-assigned multiple times.
10626*67e74705SXin Li // Only a non-trivial move assignment can observe this. We only want to
10627*67e74705SXin Li // diagnose if we implicitly define an assignment operator that assigns
10628*67e74705SXin Li // two base classes, both of which move-assign the same virtual base.
10629*67e74705SXin Li if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10630*67e74705SXin Li Class->getNumBases() < 2)
10631*67e74705SXin Li return;
10632*67e74705SXin Li
10633*67e74705SXin Li llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10634*67e74705SXin Li typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10635*67e74705SXin Li VBaseMap VBases;
10636*67e74705SXin Li
10637*67e74705SXin Li for (auto &BI : Class->bases()) {
10638*67e74705SXin Li Worklist.push_back(&BI);
10639*67e74705SXin Li while (!Worklist.empty()) {
10640*67e74705SXin Li CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10641*67e74705SXin Li CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10642*67e74705SXin Li
10643*67e74705SXin Li // If the base has no non-trivial move assignment operators,
10644*67e74705SXin Li // we don't care about moves from it.
10645*67e74705SXin Li if (!Base->hasNonTrivialMoveAssignment())
10646*67e74705SXin Li continue;
10647*67e74705SXin Li
10648*67e74705SXin Li // If there's nothing virtual here, skip it.
10649*67e74705SXin Li if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10650*67e74705SXin Li continue;
10651*67e74705SXin Li
10652*67e74705SXin Li // If we're not actually going to call a move assignment for this base,
10653*67e74705SXin Li // or the selected move assignment is trivial, skip it.
10654*67e74705SXin Li Sema::SpecialMemberOverloadResult *SMOR =
10655*67e74705SXin Li S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10656*67e74705SXin Li /*ConstArg*/false, /*VolatileArg*/false,
10657*67e74705SXin Li /*RValueThis*/true, /*ConstThis*/false,
10658*67e74705SXin Li /*VolatileThis*/false);
10659*67e74705SXin Li if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10660*67e74705SXin Li !SMOR->getMethod()->isMoveAssignmentOperator())
10661*67e74705SXin Li continue;
10662*67e74705SXin Li
10663*67e74705SXin Li if (BaseSpec->isVirtual()) {
10664*67e74705SXin Li // We're going to move-assign this virtual base, and its move
10665*67e74705SXin Li // assignment operator is not trivial. If this can happen for
10666*67e74705SXin Li // multiple distinct direct bases of Class, diagnose it. (If it
10667*67e74705SXin Li // only happens in one base, we'll diagnose it when synthesizing
10668*67e74705SXin Li // that base class's move assignment operator.)
10669*67e74705SXin Li CXXBaseSpecifier *&Existing =
10670*67e74705SXin Li VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10671*67e74705SXin Li .first->second;
10672*67e74705SXin Li if (Existing && Existing != &BI) {
10673*67e74705SXin Li S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10674*67e74705SXin Li << Class << Base;
10675*67e74705SXin Li S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10676*67e74705SXin Li << (Base->getCanonicalDecl() ==
10677*67e74705SXin Li Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10678*67e74705SXin Li << Base << Existing->getType() << Existing->getSourceRange();
10679*67e74705SXin Li S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10680*67e74705SXin Li << (Base->getCanonicalDecl() ==
10681*67e74705SXin Li BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10682*67e74705SXin Li << Base << BI.getType() << BaseSpec->getSourceRange();
10683*67e74705SXin Li
10684*67e74705SXin Li // Only diagnose each vbase once.
10685*67e74705SXin Li Existing = nullptr;
10686*67e74705SXin Li }
10687*67e74705SXin Li } else {
10688*67e74705SXin Li // Only walk over bases that have defaulted move assignment operators.
10689*67e74705SXin Li // We assume that any user-provided move assignment operator handles
10690*67e74705SXin Li // the multiple-moves-of-vbase case itself somehow.
10691*67e74705SXin Li if (!SMOR->getMethod()->isDefaulted())
10692*67e74705SXin Li continue;
10693*67e74705SXin Li
10694*67e74705SXin Li // We're going to move the base classes of Base. Add them to the list.
10695*67e74705SXin Li for (auto &BI : Base->bases())
10696*67e74705SXin Li Worklist.push_back(&BI);
10697*67e74705SXin Li }
10698*67e74705SXin Li }
10699*67e74705SXin Li }
10700*67e74705SXin Li }
10701*67e74705SXin Li
DefineImplicitMoveAssignment(SourceLocation CurrentLocation,CXXMethodDecl * MoveAssignOperator)10702*67e74705SXin Li void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10703*67e74705SXin Li CXXMethodDecl *MoveAssignOperator) {
10704*67e74705SXin Li assert((MoveAssignOperator->isDefaulted() &&
10705*67e74705SXin Li MoveAssignOperator->isOverloadedOperator() &&
10706*67e74705SXin Li MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10707*67e74705SXin Li !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10708*67e74705SXin Li !MoveAssignOperator->isDeleted()) &&
10709*67e74705SXin Li "DefineImplicitMoveAssignment called for wrong function");
10710*67e74705SXin Li
10711*67e74705SXin Li CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10712*67e74705SXin Li
10713*67e74705SXin Li if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10714*67e74705SXin Li MoveAssignOperator->setInvalidDecl();
10715*67e74705SXin Li return;
10716*67e74705SXin Li }
10717*67e74705SXin Li
10718*67e74705SXin Li MoveAssignOperator->markUsed(Context);
10719*67e74705SXin Li
10720*67e74705SXin Li SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10721*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
10722*67e74705SXin Li
10723*67e74705SXin Li // C++0x [class.copy]p28:
10724*67e74705SXin Li // The implicitly-defined or move assignment operator for a non-union class
10725*67e74705SXin Li // X performs memberwise move assignment of its subobjects. The direct base
10726*67e74705SXin Li // classes of X are assigned first, in the order of their declaration in the
10727*67e74705SXin Li // base-specifier-list, and then the immediate non-static data members of X
10728*67e74705SXin Li // are assigned, in the order in which they were declared in the class
10729*67e74705SXin Li // definition.
10730*67e74705SXin Li
10731*67e74705SXin Li // Issue a warning if our implicit move assignment operator will move
10732*67e74705SXin Li // from a virtual base more than once.
10733*67e74705SXin Li checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10734*67e74705SXin Li
10735*67e74705SXin Li // The statements that form the synthesized function body.
10736*67e74705SXin Li SmallVector<Stmt*, 8> Statements;
10737*67e74705SXin Li
10738*67e74705SXin Li // The parameter for the "other" object, which we are move from.
10739*67e74705SXin Li ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10740*67e74705SXin Li QualType OtherRefType = Other->getType()->
10741*67e74705SXin Li getAs<RValueReferenceType>()->getPointeeType();
10742*67e74705SXin Li assert(!OtherRefType.getQualifiers() &&
10743*67e74705SXin Li "Bad argument type of defaulted move assignment");
10744*67e74705SXin Li
10745*67e74705SXin Li // Our location for everything implicitly-generated.
10746*67e74705SXin Li SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10747*67e74705SXin Li ? MoveAssignOperator->getLocEnd()
10748*67e74705SXin Li : MoveAssignOperator->getLocation();
10749*67e74705SXin Li
10750*67e74705SXin Li // Builds a reference to the "other" object.
10751*67e74705SXin Li RefBuilder OtherRef(Other, OtherRefType);
10752*67e74705SXin Li // Cast to rvalue.
10753*67e74705SXin Li MoveCastBuilder MoveOther(OtherRef);
10754*67e74705SXin Li
10755*67e74705SXin Li // Builds the "this" pointer.
10756*67e74705SXin Li ThisBuilder This;
10757*67e74705SXin Li
10758*67e74705SXin Li // Assign base classes.
10759*67e74705SXin Li bool Invalid = false;
10760*67e74705SXin Li for (auto &Base : ClassDecl->bases()) {
10761*67e74705SXin Li // C++11 [class.copy]p28:
10762*67e74705SXin Li // It is unspecified whether subobjects representing virtual base classes
10763*67e74705SXin Li // are assigned more than once by the implicitly-defined copy assignment
10764*67e74705SXin Li // operator.
10765*67e74705SXin Li // FIXME: Do not assign to a vbase that will be assigned by some other base
10766*67e74705SXin Li // class. For a move-assignment, this can result in the vbase being moved
10767*67e74705SXin Li // multiple times.
10768*67e74705SXin Li
10769*67e74705SXin Li // Form the assignment:
10770*67e74705SXin Li // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10771*67e74705SXin Li QualType BaseType = Base.getType().getUnqualifiedType();
10772*67e74705SXin Li if (!BaseType->isRecordType()) {
10773*67e74705SXin Li Invalid = true;
10774*67e74705SXin Li continue;
10775*67e74705SXin Li }
10776*67e74705SXin Li
10777*67e74705SXin Li CXXCastPath BasePath;
10778*67e74705SXin Li BasePath.push_back(&Base);
10779*67e74705SXin Li
10780*67e74705SXin Li // Construct the "from" expression, which is an implicit cast to the
10781*67e74705SXin Li // appropriately-qualified base type.
10782*67e74705SXin Li CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10783*67e74705SXin Li
10784*67e74705SXin Li // Dereference "this".
10785*67e74705SXin Li DerefBuilder DerefThis(This);
10786*67e74705SXin Li
10787*67e74705SXin Li // Implicitly cast "this" to the appropriately-qualified base type.
10788*67e74705SXin Li CastBuilder To(DerefThis,
10789*67e74705SXin Li Context.getCVRQualifiedType(
10790*67e74705SXin Li BaseType, MoveAssignOperator->getTypeQualifiers()),
10791*67e74705SXin Li VK_LValue, BasePath);
10792*67e74705SXin Li
10793*67e74705SXin Li // Build the move.
10794*67e74705SXin Li StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10795*67e74705SXin Li To, From,
10796*67e74705SXin Li /*CopyingBaseSubobject=*/true,
10797*67e74705SXin Li /*Copying=*/false);
10798*67e74705SXin Li if (Move.isInvalid()) {
10799*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10800*67e74705SXin Li << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10801*67e74705SXin Li MoveAssignOperator->setInvalidDecl();
10802*67e74705SXin Li return;
10803*67e74705SXin Li }
10804*67e74705SXin Li
10805*67e74705SXin Li // Success! Record the move.
10806*67e74705SXin Li Statements.push_back(Move.getAs<Expr>());
10807*67e74705SXin Li }
10808*67e74705SXin Li
10809*67e74705SXin Li // Assign non-static members.
10810*67e74705SXin Li for (auto *Field : ClassDecl->fields()) {
10811*67e74705SXin Li // FIXME: We should form some kind of AST representation for the implied
10812*67e74705SXin Li // memcpy in a union copy operation.
10813*67e74705SXin Li if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10814*67e74705SXin Li continue;
10815*67e74705SXin Li
10816*67e74705SXin Li if (Field->isInvalidDecl()) {
10817*67e74705SXin Li Invalid = true;
10818*67e74705SXin Li continue;
10819*67e74705SXin Li }
10820*67e74705SXin Li
10821*67e74705SXin Li // Check for members of reference type; we can't move those.
10822*67e74705SXin Li if (Field->getType()->isReferenceType()) {
10823*67e74705SXin Li Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10824*67e74705SXin Li << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10825*67e74705SXin Li Diag(Field->getLocation(), diag::note_declared_at);
10826*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10827*67e74705SXin Li << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10828*67e74705SXin Li Invalid = true;
10829*67e74705SXin Li continue;
10830*67e74705SXin Li }
10831*67e74705SXin Li
10832*67e74705SXin Li // Check for members of const-qualified, non-class type.
10833*67e74705SXin Li QualType BaseType = Context.getBaseElementType(Field->getType());
10834*67e74705SXin Li if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10835*67e74705SXin Li Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10836*67e74705SXin Li << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10837*67e74705SXin Li Diag(Field->getLocation(), diag::note_declared_at);
10838*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10839*67e74705SXin Li << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10840*67e74705SXin Li Invalid = true;
10841*67e74705SXin Li continue;
10842*67e74705SXin Li }
10843*67e74705SXin Li
10844*67e74705SXin Li // Suppress assigning zero-width bitfields.
10845*67e74705SXin Li if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10846*67e74705SXin Li continue;
10847*67e74705SXin Li
10848*67e74705SXin Li QualType FieldType = Field->getType().getNonReferenceType();
10849*67e74705SXin Li if (FieldType->isIncompleteArrayType()) {
10850*67e74705SXin Li assert(ClassDecl->hasFlexibleArrayMember() &&
10851*67e74705SXin Li "Incomplete array type is not valid");
10852*67e74705SXin Li continue;
10853*67e74705SXin Li }
10854*67e74705SXin Li
10855*67e74705SXin Li // Build references to the field in the object we're copying from and to.
10856*67e74705SXin Li LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10857*67e74705SXin Li LookupMemberName);
10858*67e74705SXin Li MemberLookup.addDecl(Field);
10859*67e74705SXin Li MemberLookup.resolveKind();
10860*67e74705SXin Li MemberBuilder From(MoveOther, OtherRefType,
10861*67e74705SXin Li /*IsArrow=*/false, MemberLookup);
10862*67e74705SXin Li MemberBuilder To(This, getCurrentThisType(),
10863*67e74705SXin Li /*IsArrow=*/true, MemberLookup);
10864*67e74705SXin Li
10865*67e74705SXin Li assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10866*67e74705SXin Li "Member reference with rvalue base must be rvalue except for reference "
10867*67e74705SXin Li "members, which aren't allowed for move assignment.");
10868*67e74705SXin Li
10869*67e74705SXin Li // Build the move of this field.
10870*67e74705SXin Li StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10871*67e74705SXin Li To, From,
10872*67e74705SXin Li /*CopyingBaseSubobject=*/false,
10873*67e74705SXin Li /*Copying=*/false);
10874*67e74705SXin Li if (Move.isInvalid()) {
10875*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10876*67e74705SXin Li << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10877*67e74705SXin Li MoveAssignOperator->setInvalidDecl();
10878*67e74705SXin Li return;
10879*67e74705SXin Li }
10880*67e74705SXin Li
10881*67e74705SXin Li // Success! Record the copy.
10882*67e74705SXin Li Statements.push_back(Move.getAs<Stmt>());
10883*67e74705SXin Li }
10884*67e74705SXin Li
10885*67e74705SXin Li if (!Invalid) {
10886*67e74705SXin Li // Add a "return *this;"
10887*67e74705SXin Li ExprResult ThisObj =
10888*67e74705SXin Li CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10889*67e74705SXin Li
10890*67e74705SXin Li StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10891*67e74705SXin Li if (Return.isInvalid())
10892*67e74705SXin Li Invalid = true;
10893*67e74705SXin Li else {
10894*67e74705SXin Li Statements.push_back(Return.getAs<Stmt>());
10895*67e74705SXin Li
10896*67e74705SXin Li if (Trap.hasErrorOccurred()) {
10897*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
10898*67e74705SXin Li << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10899*67e74705SXin Li Invalid = true;
10900*67e74705SXin Li }
10901*67e74705SXin Li }
10902*67e74705SXin Li }
10903*67e74705SXin Li
10904*67e74705SXin Li // The exception specification is needed because we are defining the
10905*67e74705SXin Li // function.
10906*67e74705SXin Li ResolveExceptionSpec(CurrentLocation,
10907*67e74705SXin Li MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10908*67e74705SXin Li
10909*67e74705SXin Li if (Invalid) {
10910*67e74705SXin Li MoveAssignOperator->setInvalidDecl();
10911*67e74705SXin Li return;
10912*67e74705SXin Li }
10913*67e74705SXin Li
10914*67e74705SXin Li StmtResult Body;
10915*67e74705SXin Li {
10916*67e74705SXin Li CompoundScopeRAII CompoundScope(*this);
10917*67e74705SXin Li Body = ActOnCompoundStmt(Loc, Loc, Statements,
10918*67e74705SXin Li /*isStmtExpr=*/false);
10919*67e74705SXin Li assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10920*67e74705SXin Li }
10921*67e74705SXin Li MoveAssignOperator->setBody(Body.getAs<Stmt>());
10922*67e74705SXin Li
10923*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
10924*67e74705SXin Li L->CompletedImplicitDefinition(MoveAssignOperator);
10925*67e74705SXin Li }
10926*67e74705SXin Li }
10927*67e74705SXin Li
10928*67e74705SXin Li Sema::ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl * MD)10929*67e74705SXin Li Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10930*67e74705SXin Li CXXRecordDecl *ClassDecl = MD->getParent();
10931*67e74705SXin Li
10932*67e74705SXin Li ImplicitExceptionSpecification ExceptSpec(*this);
10933*67e74705SXin Li if (ClassDecl->isInvalidDecl())
10934*67e74705SXin Li return ExceptSpec;
10935*67e74705SXin Li
10936*67e74705SXin Li const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10937*67e74705SXin Li assert(T->getNumParams() >= 1 && "not a copy ctor");
10938*67e74705SXin Li unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10939*67e74705SXin Li
10940*67e74705SXin Li // C++ [except.spec]p14:
10941*67e74705SXin Li // An implicitly declared special member function (Clause 12) shall have an
10942*67e74705SXin Li // exception-specification. [...]
10943*67e74705SXin Li for (const auto &Base : ClassDecl->bases()) {
10944*67e74705SXin Li // Virtual bases are handled below.
10945*67e74705SXin Li if (Base.isVirtual())
10946*67e74705SXin Li continue;
10947*67e74705SXin Li
10948*67e74705SXin Li CXXRecordDecl *BaseClassDecl
10949*67e74705SXin Li = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10950*67e74705SXin Li if (CXXConstructorDecl *CopyConstructor =
10951*67e74705SXin Li LookupCopyingConstructor(BaseClassDecl, Quals))
10952*67e74705SXin Li ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10953*67e74705SXin Li }
10954*67e74705SXin Li for (const auto &Base : ClassDecl->vbases()) {
10955*67e74705SXin Li CXXRecordDecl *BaseClassDecl
10956*67e74705SXin Li = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10957*67e74705SXin Li if (CXXConstructorDecl *CopyConstructor =
10958*67e74705SXin Li LookupCopyingConstructor(BaseClassDecl, Quals))
10959*67e74705SXin Li ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10960*67e74705SXin Li }
10961*67e74705SXin Li for (const auto *Field : ClassDecl->fields()) {
10962*67e74705SXin Li QualType FieldType = Context.getBaseElementType(Field->getType());
10963*67e74705SXin Li if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10964*67e74705SXin Li if (CXXConstructorDecl *CopyConstructor =
10965*67e74705SXin Li LookupCopyingConstructor(FieldClassDecl,
10966*67e74705SXin Li Quals | FieldType.getCVRQualifiers()))
10967*67e74705SXin Li ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10968*67e74705SXin Li }
10969*67e74705SXin Li }
10970*67e74705SXin Li
10971*67e74705SXin Li return ExceptSpec;
10972*67e74705SXin Li }
10973*67e74705SXin Li
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)10974*67e74705SXin Li CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10975*67e74705SXin Li CXXRecordDecl *ClassDecl) {
10976*67e74705SXin Li // C++ [class.copy]p4:
10977*67e74705SXin Li // If the class definition does not explicitly declare a copy
10978*67e74705SXin Li // constructor, one is declared implicitly.
10979*67e74705SXin Li assert(ClassDecl->needsImplicitCopyConstructor());
10980*67e74705SXin Li
10981*67e74705SXin Li DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10982*67e74705SXin Li if (DSM.isAlreadyBeingDeclared())
10983*67e74705SXin Li return nullptr;
10984*67e74705SXin Li
10985*67e74705SXin Li QualType ClassType = Context.getTypeDeclType(ClassDecl);
10986*67e74705SXin Li QualType ArgType = ClassType;
10987*67e74705SXin Li bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10988*67e74705SXin Li if (Const)
10989*67e74705SXin Li ArgType = ArgType.withConst();
10990*67e74705SXin Li ArgType = Context.getLValueReferenceType(ArgType);
10991*67e74705SXin Li
10992*67e74705SXin Li bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10993*67e74705SXin Li CXXCopyConstructor,
10994*67e74705SXin Li Const);
10995*67e74705SXin Li
10996*67e74705SXin Li DeclarationName Name
10997*67e74705SXin Li = Context.DeclarationNames.getCXXConstructorName(
10998*67e74705SXin Li Context.getCanonicalType(ClassType));
10999*67e74705SXin Li SourceLocation ClassLoc = ClassDecl->getLocation();
11000*67e74705SXin Li DeclarationNameInfo NameInfo(Name, ClassLoc);
11001*67e74705SXin Li
11002*67e74705SXin Li // An implicitly-declared copy constructor is an inline public
11003*67e74705SXin Li // member of its class.
11004*67e74705SXin Li CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11005*67e74705SXin Li Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11006*67e74705SXin Li /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11007*67e74705SXin Li Constexpr);
11008*67e74705SXin Li CopyConstructor->setAccess(AS_public);
11009*67e74705SXin Li CopyConstructor->setDefaulted();
11010*67e74705SXin Li
11011*67e74705SXin Li if (getLangOpts().CUDA) {
11012*67e74705SXin Li inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11013*67e74705SXin Li CopyConstructor,
11014*67e74705SXin Li /* ConstRHS */ Const,
11015*67e74705SXin Li /* Diagnose */ false);
11016*67e74705SXin Li }
11017*67e74705SXin Li
11018*67e74705SXin Li // Build an exception specification pointing back at this member.
11019*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI =
11020*67e74705SXin Li getImplicitMethodEPI(*this, CopyConstructor);
11021*67e74705SXin Li CopyConstructor->setType(
11022*67e74705SXin Li Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11023*67e74705SXin Li
11024*67e74705SXin Li // Add the parameter to the constructor.
11025*67e74705SXin Li ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11026*67e74705SXin Li ClassLoc, ClassLoc,
11027*67e74705SXin Li /*IdentifierInfo=*/nullptr,
11028*67e74705SXin Li ArgType, /*TInfo=*/nullptr,
11029*67e74705SXin Li SC_None, nullptr);
11030*67e74705SXin Li CopyConstructor->setParams(FromParam);
11031*67e74705SXin Li
11032*67e74705SXin Li CopyConstructor->setTrivial(
11033*67e74705SXin Li ClassDecl->needsOverloadResolutionForCopyConstructor()
11034*67e74705SXin Li ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11035*67e74705SXin Li : ClassDecl->hasTrivialCopyConstructor());
11036*67e74705SXin Li
11037*67e74705SXin Li // Note that we have declared this constructor.
11038*67e74705SXin Li ++ASTContext::NumImplicitCopyConstructorsDeclared;
11039*67e74705SXin Li
11040*67e74705SXin Li Scope *S = getScopeForContext(ClassDecl);
11041*67e74705SXin Li CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11042*67e74705SXin Li
11043*67e74705SXin Li if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11044*67e74705SXin Li SetDeclDeleted(CopyConstructor, ClassLoc);
11045*67e74705SXin Li
11046*67e74705SXin Li if (S)
11047*67e74705SXin Li PushOnScopeChains(CopyConstructor, S, false);
11048*67e74705SXin Li ClassDecl->addDecl(CopyConstructor);
11049*67e74705SXin Li
11050*67e74705SXin Li return CopyConstructor;
11051*67e74705SXin Li }
11052*67e74705SXin Li
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)11053*67e74705SXin Li void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11054*67e74705SXin Li CXXConstructorDecl *CopyConstructor) {
11055*67e74705SXin Li assert((CopyConstructor->isDefaulted() &&
11056*67e74705SXin Li CopyConstructor->isCopyConstructor() &&
11057*67e74705SXin Li !CopyConstructor->doesThisDeclarationHaveABody() &&
11058*67e74705SXin Li !CopyConstructor->isDeleted()) &&
11059*67e74705SXin Li "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11060*67e74705SXin Li
11061*67e74705SXin Li CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11062*67e74705SXin Li assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11063*67e74705SXin Li
11064*67e74705SXin Li // C++11 [class.copy]p7:
11065*67e74705SXin Li // The [definition of an implicitly declared copy constructor] is
11066*67e74705SXin Li // deprecated if the class has a user-declared copy assignment operator
11067*67e74705SXin Li // or a user-declared destructor.
11068*67e74705SXin Li if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11069*67e74705SXin Li diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11070*67e74705SXin Li
11071*67e74705SXin Li SynthesizedFunctionScope Scope(*this, CopyConstructor);
11072*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
11073*67e74705SXin Li
11074*67e74705SXin Li if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11075*67e74705SXin Li Trap.hasErrorOccurred()) {
11076*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
11077*67e74705SXin Li << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11078*67e74705SXin Li CopyConstructor->setInvalidDecl();
11079*67e74705SXin Li } else {
11080*67e74705SXin Li SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11081*67e74705SXin Li ? CopyConstructor->getLocEnd()
11082*67e74705SXin Li : CopyConstructor->getLocation();
11083*67e74705SXin Li Sema::CompoundScopeRAII CompoundScope(*this);
11084*67e74705SXin Li CopyConstructor->setBody(
11085*67e74705SXin Li ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11086*67e74705SXin Li }
11087*67e74705SXin Li
11088*67e74705SXin Li // The exception specification is needed because we are defining the
11089*67e74705SXin Li // function.
11090*67e74705SXin Li ResolveExceptionSpec(CurrentLocation,
11091*67e74705SXin Li CopyConstructor->getType()->castAs<FunctionProtoType>());
11092*67e74705SXin Li
11093*67e74705SXin Li CopyConstructor->markUsed(Context);
11094*67e74705SXin Li MarkVTableUsed(CurrentLocation, ClassDecl);
11095*67e74705SXin Li
11096*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
11097*67e74705SXin Li L->CompletedImplicitDefinition(CopyConstructor);
11098*67e74705SXin Li }
11099*67e74705SXin Li }
11100*67e74705SXin Li
11101*67e74705SXin Li Sema::ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl * MD)11102*67e74705SXin Li Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11103*67e74705SXin Li CXXRecordDecl *ClassDecl = MD->getParent();
11104*67e74705SXin Li
11105*67e74705SXin Li // C++ [except.spec]p14:
11106*67e74705SXin Li // An implicitly declared special member function (Clause 12) shall have an
11107*67e74705SXin Li // exception-specification. [...]
11108*67e74705SXin Li ImplicitExceptionSpecification ExceptSpec(*this);
11109*67e74705SXin Li if (ClassDecl->isInvalidDecl())
11110*67e74705SXin Li return ExceptSpec;
11111*67e74705SXin Li
11112*67e74705SXin Li // Direct base-class constructors.
11113*67e74705SXin Li for (const auto &B : ClassDecl->bases()) {
11114*67e74705SXin Li if (B.isVirtual()) // Handled below.
11115*67e74705SXin Li continue;
11116*67e74705SXin Li
11117*67e74705SXin Li if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11118*67e74705SXin Li CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11119*67e74705SXin Li CXXConstructorDecl *Constructor =
11120*67e74705SXin Li LookupMovingConstructor(BaseClassDecl, 0);
11121*67e74705SXin Li // If this is a deleted function, add it anyway. This might be conformant
11122*67e74705SXin Li // with the standard. This might not. I'm not sure. It might not matter.
11123*67e74705SXin Li if (Constructor)
11124*67e74705SXin Li ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11125*67e74705SXin Li }
11126*67e74705SXin Li }
11127*67e74705SXin Li
11128*67e74705SXin Li // Virtual base-class constructors.
11129*67e74705SXin Li for (const auto &B : ClassDecl->vbases()) {
11130*67e74705SXin Li if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11131*67e74705SXin Li CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11132*67e74705SXin Li CXXConstructorDecl *Constructor =
11133*67e74705SXin Li LookupMovingConstructor(BaseClassDecl, 0);
11134*67e74705SXin Li // If this is a deleted function, add it anyway. This might be conformant
11135*67e74705SXin Li // with the standard. This might not. I'm not sure. It might not matter.
11136*67e74705SXin Li if (Constructor)
11137*67e74705SXin Li ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11138*67e74705SXin Li }
11139*67e74705SXin Li }
11140*67e74705SXin Li
11141*67e74705SXin Li // Field constructors.
11142*67e74705SXin Li for (const auto *F : ClassDecl->fields()) {
11143*67e74705SXin Li QualType FieldType = Context.getBaseElementType(F->getType());
11144*67e74705SXin Li if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11145*67e74705SXin Li CXXConstructorDecl *Constructor =
11146*67e74705SXin Li LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11147*67e74705SXin Li // If this is a deleted function, add it anyway. This might be conformant
11148*67e74705SXin Li // with the standard. This might not. I'm not sure. It might not matter.
11149*67e74705SXin Li // In particular, the problem is that this function never gets called. It
11150*67e74705SXin Li // might just be ill-formed because this function attempts to refer to
11151*67e74705SXin Li // a deleted function here.
11152*67e74705SXin Li if (Constructor)
11153*67e74705SXin Li ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11154*67e74705SXin Li }
11155*67e74705SXin Li }
11156*67e74705SXin Li
11157*67e74705SXin Li return ExceptSpec;
11158*67e74705SXin Li }
11159*67e74705SXin Li
DeclareImplicitMoveConstructor(CXXRecordDecl * ClassDecl)11160*67e74705SXin Li CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11161*67e74705SXin Li CXXRecordDecl *ClassDecl) {
11162*67e74705SXin Li assert(ClassDecl->needsImplicitMoveConstructor());
11163*67e74705SXin Li
11164*67e74705SXin Li DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11165*67e74705SXin Li if (DSM.isAlreadyBeingDeclared())
11166*67e74705SXin Li return nullptr;
11167*67e74705SXin Li
11168*67e74705SXin Li QualType ClassType = Context.getTypeDeclType(ClassDecl);
11169*67e74705SXin Li QualType ArgType = Context.getRValueReferenceType(ClassType);
11170*67e74705SXin Li
11171*67e74705SXin Li bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11172*67e74705SXin Li CXXMoveConstructor,
11173*67e74705SXin Li false);
11174*67e74705SXin Li
11175*67e74705SXin Li DeclarationName Name
11176*67e74705SXin Li = Context.DeclarationNames.getCXXConstructorName(
11177*67e74705SXin Li Context.getCanonicalType(ClassType));
11178*67e74705SXin Li SourceLocation ClassLoc = ClassDecl->getLocation();
11179*67e74705SXin Li DeclarationNameInfo NameInfo(Name, ClassLoc);
11180*67e74705SXin Li
11181*67e74705SXin Li // C++11 [class.copy]p11:
11182*67e74705SXin Li // An implicitly-declared copy/move constructor is an inline public
11183*67e74705SXin Li // member of its class.
11184*67e74705SXin Li CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11185*67e74705SXin Li Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11186*67e74705SXin Li /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11187*67e74705SXin Li Constexpr);
11188*67e74705SXin Li MoveConstructor->setAccess(AS_public);
11189*67e74705SXin Li MoveConstructor->setDefaulted();
11190*67e74705SXin Li
11191*67e74705SXin Li if (getLangOpts().CUDA) {
11192*67e74705SXin Li inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11193*67e74705SXin Li MoveConstructor,
11194*67e74705SXin Li /* ConstRHS */ false,
11195*67e74705SXin Li /* Diagnose */ false);
11196*67e74705SXin Li }
11197*67e74705SXin Li
11198*67e74705SXin Li // Build an exception specification pointing back at this member.
11199*67e74705SXin Li FunctionProtoType::ExtProtoInfo EPI =
11200*67e74705SXin Li getImplicitMethodEPI(*this, MoveConstructor);
11201*67e74705SXin Li MoveConstructor->setType(
11202*67e74705SXin Li Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11203*67e74705SXin Li
11204*67e74705SXin Li // Add the parameter to the constructor.
11205*67e74705SXin Li ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11206*67e74705SXin Li ClassLoc, ClassLoc,
11207*67e74705SXin Li /*IdentifierInfo=*/nullptr,
11208*67e74705SXin Li ArgType, /*TInfo=*/nullptr,
11209*67e74705SXin Li SC_None, nullptr);
11210*67e74705SXin Li MoveConstructor->setParams(FromParam);
11211*67e74705SXin Li
11212*67e74705SXin Li MoveConstructor->setTrivial(
11213*67e74705SXin Li ClassDecl->needsOverloadResolutionForMoveConstructor()
11214*67e74705SXin Li ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11215*67e74705SXin Li : ClassDecl->hasTrivialMoveConstructor());
11216*67e74705SXin Li
11217*67e74705SXin Li // Note that we have declared this constructor.
11218*67e74705SXin Li ++ASTContext::NumImplicitMoveConstructorsDeclared;
11219*67e74705SXin Li
11220*67e74705SXin Li Scope *S = getScopeForContext(ClassDecl);
11221*67e74705SXin Li CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
11222*67e74705SXin Li
11223*67e74705SXin Li if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11224*67e74705SXin Li ClassDecl->setImplicitMoveConstructorIsDeleted();
11225*67e74705SXin Li SetDeclDeleted(MoveConstructor, ClassLoc);
11226*67e74705SXin Li }
11227*67e74705SXin Li
11228*67e74705SXin Li if (S)
11229*67e74705SXin Li PushOnScopeChains(MoveConstructor, S, false);
11230*67e74705SXin Li ClassDecl->addDecl(MoveConstructor);
11231*67e74705SXin Li
11232*67e74705SXin Li return MoveConstructor;
11233*67e74705SXin Li }
11234*67e74705SXin Li
DefineImplicitMoveConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * MoveConstructor)11235*67e74705SXin Li void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11236*67e74705SXin Li CXXConstructorDecl *MoveConstructor) {
11237*67e74705SXin Li assert((MoveConstructor->isDefaulted() &&
11238*67e74705SXin Li MoveConstructor->isMoveConstructor() &&
11239*67e74705SXin Li !MoveConstructor->doesThisDeclarationHaveABody() &&
11240*67e74705SXin Li !MoveConstructor->isDeleted()) &&
11241*67e74705SXin Li "DefineImplicitMoveConstructor - call it for implicit move ctor");
11242*67e74705SXin Li
11243*67e74705SXin Li CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11244*67e74705SXin Li assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11245*67e74705SXin Li
11246*67e74705SXin Li SynthesizedFunctionScope Scope(*this, MoveConstructor);
11247*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
11248*67e74705SXin Li
11249*67e74705SXin Li if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11250*67e74705SXin Li Trap.hasErrorOccurred()) {
11251*67e74705SXin Li Diag(CurrentLocation, diag::note_member_synthesized_at)
11252*67e74705SXin Li << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11253*67e74705SXin Li MoveConstructor->setInvalidDecl();
11254*67e74705SXin Li } else {
11255*67e74705SXin Li SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11256*67e74705SXin Li ? MoveConstructor->getLocEnd()
11257*67e74705SXin Li : MoveConstructor->getLocation();
11258*67e74705SXin Li Sema::CompoundScopeRAII CompoundScope(*this);
11259*67e74705SXin Li MoveConstructor->setBody(ActOnCompoundStmt(
11260*67e74705SXin Li Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11261*67e74705SXin Li }
11262*67e74705SXin Li
11263*67e74705SXin Li // The exception specification is needed because we are defining the
11264*67e74705SXin Li // function.
11265*67e74705SXin Li ResolveExceptionSpec(CurrentLocation,
11266*67e74705SXin Li MoveConstructor->getType()->castAs<FunctionProtoType>());
11267*67e74705SXin Li
11268*67e74705SXin Li MoveConstructor->markUsed(Context);
11269*67e74705SXin Li MarkVTableUsed(CurrentLocation, ClassDecl);
11270*67e74705SXin Li
11271*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
11272*67e74705SXin Li L->CompletedImplicitDefinition(MoveConstructor);
11273*67e74705SXin Li }
11274*67e74705SXin Li }
11275*67e74705SXin Li
isImplicitlyDeleted(FunctionDecl * FD)11276*67e74705SXin Li bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11277*67e74705SXin Li return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11278*67e74705SXin Li }
11279*67e74705SXin Li
DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)11280*67e74705SXin Li void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11281*67e74705SXin Li SourceLocation CurrentLocation,
11282*67e74705SXin Li CXXConversionDecl *Conv) {
11283*67e74705SXin Li CXXRecordDecl *Lambda = Conv->getParent();
11284*67e74705SXin Li CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11285*67e74705SXin Li // If we are defining a specialization of a conversion to function-ptr
11286*67e74705SXin Li // cache the deduced template arguments for this specialization
11287*67e74705SXin Li // so that we can use them to retrieve the corresponding call-operator
11288*67e74705SXin Li // and static-invoker.
11289*67e74705SXin Li const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11290*67e74705SXin Li
11291*67e74705SXin Li // Retrieve the corresponding call-operator specialization.
11292*67e74705SXin Li if (Lambda->isGenericLambda()) {
11293*67e74705SXin Li assert(Conv->isFunctionTemplateSpecialization());
11294*67e74705SXin Li FunctionTemplateDecl *CallOpTemplate =
11295*67e74705SXin Li CallOp->getDescribedFunctionTemplate();
11296*67e74705SXin Li DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11297*67e74705SXin Li void *InsertPos = nullptr;
11298*67e74705SXin Li FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11299*67e74705SXin Li DeducedTemplateArgs->asArray(),
11300*67e74705SXin Li InsertPos);
11301*67e74705SXin Li assert(CallOpSpec &&
11302*67e74705SXin Li "Conversion operator must have a corresponding call operator");
11303*67e74705SXin Li CallOp = cast<CXXMethodDecl>(CallOpSpec);
11304*67e74705SXin Li }
11305*67e74705SXin Li // Mark the call operator referenced (and add to pending instantiations
11306*67e74705SXin Li // if necessary).
11307*67e74705SXin Li // For both the conversion and static-invoker template specializations
11308*67e74705SXin Li // we construct their body's in this function, so no need to add them
11309*67e74705SXin Li // to the PendingInstantiations.
11310*67e74705SXin Li MarkFunctionReferenced(CurrentLocation, CallOp);
11311*67e74705SXin Li
11312*67e74705SXin Li SynthesizedFunctionScope Scope(*this, Conv);
11313*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
11314*67e74705SXin Li
11315*67e74705SXin Li // Retrieve the static invoker...
11316*67e74705SXin Li CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11317*67e74705SXin Li // ... and get the corresponding specialization for a generic lambda.
11318*67e74705SXin Li if (Lambda->isGenericLambda()) {
11319*67e74705SXin Li assert(DeducedTemplateArgs &&
11320*67e74705SXin Li "Must have deduced template arguments from Conversion Operator");
11321*67e74705SXin Li FunctionTemplateDecl *InvokeTemplate =
11322*67e74705SXin Li Invoker->getDescribedFunctionTemplate();
11323*67e74705SXin Li void *InsertPos = nullptr;
11324*67e74705SXin Li FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11325*67e74705SXin Li DeducedTemplateArgs->asArray(),
11326*67e74705SXin Li InsertPos);
11327*67e74705SXin Li assert(InvokeSpec &&
11328*67e74705SXin Li "Must have a corresponding static invoker specialization");
11329*67e74705SXin Li Invoker = cast<CXXMethodDecl>(InvokeSpec);
11330*67e74705SXin Li }
11331*67e74705SXin Li // Construct the body of the conversion function { return __invoke; }.
11332*67e74705SXin Li Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11333*67e74705SXin Li VK_LValue, Conv->getLocation()).get();
11334*67e74705SXin Li assert(FunctionRef && "Can't refer to __invoke function?");
11335*67e74705SXin Li Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11336*67e74705SXin Li Conv->setBody(new (Context) CompoundStmt(Context, Return,
11337*67e74705SXin Li Conv->getLocation(),
11338*67e74705SXin Li Conv->getLocation()));
11339*67e74705SXin Li
11340*67e74705SXin Li Conv->markUsed(Context);
11341*67e74705SXin Li Conv->setReferenced();
11342*67e74705SXin Li
11343*67e74705SXin Li // Fill in the __invoke function with a dummy implementation. IR generation
11344*67e74705SXin Li // will fill in the actual details.
11345*67e74705SXin Li Invoker->markUsed(Context);
11346*67e74705SXin Li Invoker->setReferenced();
11347*67e74705SXin Li Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11348*67e74705SXin Li
11349*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
11350*67e74705SXin Li L->CompletedImplicitDefinition(Conv);
11351*67e74705SXin Li L->CompletedImplicitDefinition(Invoker);
11352*67e74705SXin Li }
11353*67e74705SXin Li }
11354*67e74705SXin Li
11355*67e74705SXin Li
11356*67e74705SXin Li
DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLocation,CXXConversionDecl * Conv)11357*67e74705SXin Li void Sema::DefineImplicitLambdaToBlockPointerConversion(
11358*67e74705SXin Li SourceLocation CurrentLocation,
11359*67e74705SXin Li CXXConversionDecl *Conv)
11360*67e74705SXin Li {
11361*67e74705SXin Li assert(!Conv->getParent()->isGenericLambda());
11362*67e74705SXin Li
11363*67e74705SXin Li Conv->markUsed(Context);
11364*67e74705SXin Li
11365*67e74705SXin Li SynthesizedFunctionScope Scope(*this, Conv);
11366*67e74705SXin Li DiagnosticErrorTrap Trap(Diags);
11367*67e74705SXin Li
11368*67e74705SXin Li // Copy-initialize the lambda object as needed to capture it.
11369*67e74705SXin Li Expr *This = ActOnCXXThis(CurrentLocation).get();
11370*67e74705SXin Li Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11371*67e74705SXin Li
11372*67e74705SXin Li ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11373*67e74705SXin Li Conv->getLocation(),
11374*67e74705SXin Li Conv, DerefThis);
11375*67e74705SXin Li
11376*67e74705SXin Li // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11377*67e74705SXin Li // behavior. Note that only the general conversion function does this
11378*67e74705SXin Li // (since it's unusable otherwise); in the case where we inline the
11379*67e74705SXin Li // block literal, it has block literal lifetime semantics.
11380*67e74705SXin Li if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11381*67e74705SXin Li BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11382*67e74705SXin Li CK_CopyAndAutoreleaseBlockObject,
11383*67e74705SXin Li BuildBlock.get(), nullptr, VK_RValue);
11384*67e74705SXin Li
11385*67e74705SXin Li if (BuildBlock.isInvalid()) {
11386*67e74705SXin Li Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11387*67e74705SXin Li Conv->setInvalidDecl();
11388*67e74705SXin Li return;
11389*67e74705SXin Li }
11390*67e74705SXin Li
11391*67e74705SXin Li // Create the return statement that returns the block from the conversion
11392*67e74705SXin Li // function.
11393*67e74705SXin Li StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11394*67e74705SXin Li if (Return.isInvalid()) {
11395*67e74705SXin Li Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11396*67e74705SXin Li Conv->setInvalidDecl();
11397*67e74705SXin Li return;
11398*67e74705SXin Li }
11399*67e74705SXin Li
11400*67e74705SXin Li // Set the body of the conversion function.
11401*67e74705SXin Li Stmt *ReturnS = Return.get();
11402*67e74705SXin Li Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11403*67e74705SXin Li Conv->getLocation(),
11404*67e74705SXin Li Conv->getLocation()));
11405*67e74705SXin Li
11406*67e74705SXin Li // We're done; notify the mutation listener, if any.
11407*67e74705SXin Li if (ASTMutationListener *L = getASTMutationListener()) {
11408*67e74705SXin Li L->CompletedImplicitDefinition(Conv);
11409*67e74705SXin Li }
11410*67e74705SXin Li }
11411*67e74705SXin Li
11412*67e74705SXin Li /// \brief Determine whether the given list arguments contains exactly one
11413*67e74705SXin Li /// "real" (non-default) argument.
hasOneRealArgument(MultiExprArg Args)11414*67e74705SXin Li static bool hasOneRealArgument(MultiExprArg Args) {
11415*67e74705SXin Li switch (Args.size()) {
11416*67e74705SXin Li case 0:
11417*67e74705SXin Li return false;
11418*67e74705SXin Li
11419*67e74705SXin Li default:
11420*67e74705SXin Li if (!Args[1]->isDefaultArgument())
11421*67e74705SXin Li return false;
11422*67e74705SXin Li
11423*67e74705SXin Li // fall through
11424*67e74705SXin Li case 1:
11425*67e74705SXin Li return !Args[0]->isDefaultArgument();
11426*67e74705SXin Li }
11427*67e74705SXin Li
11428*67e74705SXin Li return false;
11429*67e74705SXin Li }
11430*67e74705SXin Li
11431*67e74705SXin Li ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,NamedDecl * FoundDecl,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)11432*67e74705SXin Li Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11433*67e74705SXin Li NamedDecl *FoundDecl,
11434*67e74705SXin Li CXXConstructorDecl *Constructor,
11435*67e74705SXin Li MultiExprArg ExprArgs,
11436*67e74705SXin Li bool HadMultipleCandidates,
11437*67e74705SXin Li bool IsListInitialization,
11438*67e74705SXin Li bool IsStdInitListInitialization,
11439*67e74705SXin Li bool RequiresZeroInit,
11440*67e74705SXin Li unsigned ConstructKind,
11441*67e74705SXin Li SourceRange ParenRange) {
11442*67e74705SXin Li bool Elidable = false;
11443*67e74705SXin Li
11444*67e74705SXin Li // C++0x [class.copy]p34:
11445*67e74705SXin Li // When certain criteria are met, an implementation is allowed to
11446*67e74705SXin Li // omit the copy/move construction of a class object, even if the
11447*67e74705SXin Li // copy/move constructor and/or destructor for the object have
11448*67e74705SXin Li // side effects. [...]
11449*67e74705SXin Li // - when a temporary class object that has not been bound to a
11450*67e74705SXin Li // reference (12.2) would be copied/moved to a class object
11451*67e74705SXin Li // with the same cv-unqualified type, the copy/move operation
11452*67e74705SXin Li // can be omitted by constructing the temporary object
11453*67e74705SXin Li // directly into the target of the omitted copy/move
11454*67e74705SXin Li if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
11455*67e74705SXin Li Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11456*67e74705SXin Li Expr *SubExpr = ExprArgs[0];
11457*67e74705SXin Li Elidable = SubExpr->isTemporaryObject(
11458*67e74705SXin Li Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
11459*67e74705SXin Li }
11460*67e74705SXin Li
11461*67e74705SXin Li return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
11462*67e74705SXin Li FoundDecl, Constructor,
11463*67e74705SXin Li Elidable, ExprArgs, HadMultipleCandidates,
11464*67e74705SXin Li IsListInitialization,
11465*67e74705SXin Li IsStdInitListInitialization, RequiresZeroInit,
11466*67e74705SXin Li ConstructKind, ParenRange);
11467*67e74705SXin Li }
11468*67e74705SXin Li
11469*67e74705SXin Li ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,NamedDecl * FoundDecl,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)11470*67e74705SXin Li Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11471*67e74705SXin Li NamedDecl *FoundDecl,
11472*67e74705SXin Li CXXConstructorDecl *Constructor,
11473*67e74705SXin Li bool Elidable,
11474*67e74705SXin Li MultiExprArg ExprArgs,
11475*67e74705SXin Li bool HadMultipleCandidates,
11476*67e74705SXin Li bool IsListInitialization,
11477*67e74705SXin Li bool IsStdInitListInitialization,
11478*67e74705SXin Li bool RequiresZeroInit,
11479*67e74705SXin Li unsigned ConstructKind,
11480*67e74705SXin Li SourceRange ParenRange) {
11481*67e74705SXin Li if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
11482*67e74705SXin Li Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
11483*67e74705SXin Li if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
11484*67e74705SXin Li return ExprError();
11485*67e74705SXin Li }
11486*67e74705SXin Li
11487*67e74705SXin Li return BuildCXXConstructExpr(
11488*67e74705SXin Li ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
11489*67e74705SXin Li HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11490*67e74705SXin Li RequiresZeroInit, ConstructKind, ParenRange);
11491*67e74705SXin Li }
11492*67e74705SXin Li
11493*67e74705SXin Li /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11494*67e74705SXin Li /// including handling of its default argument expressions.
11495*67e74705SXin Li ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool HadMultipleCandidates,bool IsListInitialization,bool IsStdInitListInitialization,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)11496*67e74705SXin Li Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11497*67e74705SXin Li CXXConstructorDecl *Constructor,
11498*67e74705SXin Li bool Elidable,
11499*67e74705SXin Li MultiExprArg ExprArgs,
11500*67e74705SXin Li bool HadMultipleCandidates,
11501*67e74705SXin Li bool IsListInitialization,
11502*67e74705SXin Li bool IsStdInitListInitialization,
11503*67e74705SXin Li bool RequiresZeroInit,
11504*67e74705SXin Li unsigned ConstructKind,
11505*67e74705SXin Li SourceRange ParenRange) {
11506*67e74705SXin Li assert(declaresSameEntity(
11507*67e74705SXin Li Constructor->getParent(),
11508*67e74705SXin Li DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
11509*67e74705SXin Li "given constructor for wrong type");
11510*67e74705SXin Li MarkFunctionReferenced(ConstructLoc, Constructor);
11511*67e74705SXin Li
11512*67e74705SXin Li return CXXConstructExpr::Create(
11513*67e74705SXin Li Context, DeclInitType, ConstructLoc, Constructor, Elidable,
11514*67e74705SXin Li ExprArgs, HadMultipleCandidates, IsListInitialization,
11515*67e74705SXin Li IsStdInitListInitialization, RequiresZeroInit,
11516*67e74705SXin Li static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11517*67e74705SXin Li ParenRange);
11518*67e74705SXin Li }
11519*67e74705SXin Li
BuildCXXDefaultInitExpr(SourceLocation Loc,FieldDecl * Field)11520*67e74705SXin Li ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11521*67e74705SXin Li assert(Field->hasInClassInitializer());
11522*67e74705SXin Li
11523*67e74705SXin Li // If we already have the in-class initializer nothing needs to be done.
11524*67e74705SXin Li if (Field->getInClassInitializer())
11525*67e74705SXin Li return CXXDefaultInitExpr::Create(Context, Loc, Field);
11526*67e74705SXin Li
11527*67e74705SXin Li // Maybe we haven't instantiated the in-class initializer. Go check the
11528*67e74705SXin Li // pattern FieldDecl to see if it has one.
11529*67e74705SXin Li CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11530*67e74705SXin Li
11531*67e74705SXin Li if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11532*67e74705SXin Li CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11533*67e74705SXin Li DeclContext::lookup_result Lookup =
11534*67e74705SXin Li ClassPattern->lookup(Field->getDeclName());
11535*67e74705SXin Li
11536*67e74705SXin Li // Lookup can return at most two results: the pattern for the field, or the
11537*67e74705SXin Li // injected class name of the parent record. No other member can have the
11538*67e74705SXin Li // same name as the field.
11539*67e74705SXin Li assert(!Lookup.empty() && Lookup.size() <= 2 &&
11540*67e74705SXin Li "more than two lookup results for field name");
11541*67e74705SXin Li FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
11542*67e74705SXin Li if (!Pattern) {
11543*67e74705SXin Li assert(isa<CXXRecordDecl>(Lookup[0]) &&
11544*67e74705SXin Li "cannot have other non-field member with same name");
11545*67e74705SXin Li Pattern = cast<FieldDecl>(Lookup[1]);
11546*67e74705SXin Li }
11547*67e74705SXin Li
11548*67e74705SXin Li if (InstantiateInClassInitializer(Loc, Field, Pattern,
11549*67e74705SXin Li getTemplateInstantiationArgs(Field)))
11550*67e74705SXin Li return ExprError();
11551*67e74705SXin Li return CXXDefaultInitExpr::Create(Context, Loc, Field);
11552*67e74705SXin Li }
11553*67e74705SXin Li
11554*67e74705SXin Li // DR1351:
11555*67e74705SXin Li // If the brace-or-equal-initializer of a non-static data member
11556*67e74705SXin Li // invokes a defaulted default constructor of its class or of an
11557*67e74705SXin Li // enclosing class in a potentially evaluated subexpression, the
11558*67e74705SXin Li // program is ill-formed.
11559*67e74705SXin Li //
11560*67e74705SXin Li // This resolution is unworkable: the exception specification of the
11561*67e74705SXin Li // default constructor can be needed in an unevaluated context, in
11562*67e74705SXin Li // particular, in the operand of a noexcept-expression, and we can be
11563*67e74705SXin Li // unable to compute an exception specification for an enclosed class.
11564*67e74705SXin Li //
11565*67e74705SXin Li // Any attempt to resolve the exception specification of a defaulted default
11566*67e74705SXin Li // constructor before the initializer is lexically complete will ultimately
11567*67e74705SXin Li // come here at which point we can diagnose it.
11568*67e74705SXin Li RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11569*67e74705SXin Li if (OutermostClass == ParentRD) {
11570*67e74705SXin Li Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11571*67e74705SXin Li << ParentRD << Field;
11572*67e74705SXin Li } else {
11573*67e74705SXin Li Diag(Field->getLocEnd(),
11574*67e74705SXin Li diag::err_in_class_initializer_not_yet_parsed_outer_class)
11575*67e74705SXin Li << ParentRD << OutermostClass << Field;
11576*67e74705SXin Li }
11577*67e74705SXin Li
11578*67e74705SXin Li return ExprError();
11579*67e74705SXin Li }
11580*67e74705SXin Li
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)11581*67e74705SXin Li void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11582*67e74705SXin Li if (VD->isInvalidDecl()) return;
11583*67e74705SXin Li
11584*67e74705SXin Li CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11585*67e74705SXin Li if (ClassDecl->isInvalidDecl()) return;
11586*67e74705SXin Li if (ClassDecl->hasIrrelevantDestructor()) return;
11587*67e74705SXin Li if (ClassDecl->isDependentContext()) return;
11588*67e74705SXin Li
11589*67e74705SXin Li CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11590*67e74705SXin Li MarkFunctionReferenced(VD->getLocation(), Destructor);
11591*67e74705SXin Li CheckDestructorAccess(VD->getLocation(), Destructor,
11592*67e74705SXin Li PDiag(diag::err_access_dtor_var)
11593*67e74705SXin Li << VD->getDeclName()
11594*67e74705SXin Li << VD->getType());
11595*67e74705SXin Li DiagnoseUseOfDecl(Destructor, VD->getLocation());
11596*67e74705SXin Li
11597*67e74705SXin Li if (Destructor->isTrivial()) return;
11598*67e74705SXin Li if (!VD->hasGlobalStorage()) return;
11599*67e74705SXin Li
11600*67e74705SXin Li // Emit warning for non-trivial dtor in global scope (a real global,
11601*67e74705SXin Li // class-static, function-static).
11602*67e74705SXin Li Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11603*67e74705SXin Li
11604*67e74705SXin Li // TODO: this should be re-enabled for static locals by !CXAAtExit
11605*67e74705SXin Li if (!VD->isStaticLocal())
11606*67e74705SXin Li Diag(VD->getLocation(), diag::warn_global_destructor);
11607*67e74705SXin Li }
11608*67e74705SXin Li
11609*67e74705SXin Li /// \brief Given a constructor and the set of arguments provided for the
11610*67e74705SXin Li /// constructor, convert the arguments and add any required default arguments
11611*67e74705SXin Li /// to form a proper call to this constructor.
11612*67e74705SXin Li ///
11613*67e74705SXin Li /// \returns true if an error occurred, false otherwise.
11614*67e74705SXin Li bool
CompleteConstructorCall(CXXConstructorDecl * Constructor,MultiExprArg ArgsPtr,SourceLocation Loc,SmallVectorImpl<Expr * > & ConvertedArgs,bool AllowExplicit,bool IsListInitialization)11615*67e74705SXin Li Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11616*67e74705SXin Li MultiExprArg ArgsPtr,
11617*67e74705SXin Li SourceLocation Loc,
11618*67e74705SXin Li SmallVectorImpl<Expr*> &ConvertedArgs,
11619*67e74705SXin Li bool AllowExplicit,
11620*67e74705SXin Li bool IsListInitialization) {
11621*67e74705SXin Li // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11622*67e74705SXin Li unsigned NumArgs = ArgsPtr.size();
11623*67e74705SXin Li Expr **Args = ArgsPtr.data();
11624*67e74705SXin Li
11625*67e74705SXin Li const FunctionProtoType *Proto
11626*67e74705SXin Li = Constructor->getType()->getAs<FunctionProtoType>();
11627*67e74705SXin Li assert(Proto && "Constructor without a prototype?");
11628*67e74705SXin Li unsigned NumParams = Proto->getNumParams();
11629*67e74705SXin Li
11630*67e74705SXin Li // If too few arguments are available, we'll fill in the rest with defaults.
11631*67e74705SXin Li if (NumArgs < NumParams)
11632*67e74705SXin Li ConvertedArgs.reserve(NumParams);
11633*67e74705SXin Li else
11634*67e74705SXin Li ConvertedArgs.reserve(NumArgs);
11635*67e74705SXin Li
11636*67e74705SXin Li VariadicCallType CallType =
11637*67e74705SXin Li Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11638*67e74705SXin Li SmallVector<Expr *, 8> AllArgs;
11639*67e74705SXin Li bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11640*67e74705SXin Li Proto, 0,
11641*67e74705SXin Li llvm::makeArrayRef(Args, NumArgs),
11642*67e74705SXin Li AllArgs,
11643*67e74705SXin Li CallType, AllowExplicit,
11644*67e74705SXin Li IsListInitialization);
11645*67e74705SXin Li ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11646*67e74705SXin Li
11647*67e74705SXin Li DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11648*67e74705SXin Li
11649*67e74705SXin Li CheckConstructorCall(Constructor,
11650*67e74705SXin Li llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11651*67e74705SXin Li Proto, Loc);
11652*67e74705SXin Li
11653*67e74705SXin Li return Invalid;
11654*67e74705SXin Li }
11655*67e74705SXin Li
11656*67e74705SXin Li static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)11657*67e74705SXin Li CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11658*67e74705SXin Li const FunctionDecl *FnDecl) {
11659*67e74705SXin Li const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11660*67e74705SXin Li if (isa<NamespaceDecl>(DC)) {
11661*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(),
11662*67e74705SXin Li diag::err_operator_new_delete_declared_in_namespace)
11663*67e74705SXin Li << FnDecl->getDeclName();
11664*67e74705SXin Li }
11665*67e74705SXin Li
11666*67e74705SXin Li if (isa<TranslationUnitDecl>(DC) &&
11667*67e74705SXin Li FnDecl->getStorageClass() == SC_Static) {
11668*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(),
11669*67e74705SXin Li diag::err_operator_new_delete_declared_static)
11670*67e74705SXin Li << FnDecl->getDeclName();
11671*67e74705SXin Li }
11672*67e74705SXin Li
11673*67e74705SXin Li return false;
11674*67e74705SXin Li }
11675*67e74705SXin Li
11676*67e74705SXin Li static inline bool
CheckOperatorNewDeleteTypes(Sema & SemaRef,const FunctionDecl * FnDecl,CanQualType ExpectedResultType,CanQualType ExpectedFirstParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)11677*67e74705SXin Li CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11678*67e74705SXin Li CanQualType ExpectedResultType,
11679*67e74705SXin Li CanQualType ExpectedFirstParamType,
11680*67e74705SXin Li unsigned DependentParamTypeDiag,
11681*67e74705SXin Li unsigned InvalidParamTypeDiag) {
11682*67e74705SXin Li QualType ResultType =
11683*67e74705SXin Li FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11684*67e74705SXin Li
11685*67e74705SXin Li // Check that the result type is not dependent.
11686*67e74705SXin Li if (ResultType->isDependentType())
11687*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(),
11688*67e74705SXin Li diag::err_operator_new_delete_dependent_result_type)
11689*67e74705SXin Li << FnDecl->getDeclName() << ExpectedResultType;
11690*67e74705SXin Li
11691*67e74705SXin Li // Check that the result type is what we expect.
11692*67e74705SXin Li if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11693*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(),
11694*67e74705SXin Li diag::err_operator_new_delete_invalid_result_type)
11695*67e74705SXin Li << FnDecl->getDeclName() << ExpectedResultType;
11696*67e74705SXin Li
11697*67e74705SXin Li // A function template must have at least 2 parameters.
11698*67e74705SXin Li if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11699*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(),
11700*67e74705SXin Li diag::err_operator_new_delete_template_too_few_parameters)
11701*67e74705SXin Li << FnDecl->getDeclName();
11702*67e74705SXin Li
11703*67e74705SXin Li // The function decl must have at least 1 parameter.
11704*67e74705SXin Li if (FnDecl->getNumParams() == 0)
11705*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(),
11706*67e74705SXin Li diag::err_operator_new_delete_too_few_parameters)
11707*67e74705SXin Li << FnDecl->getDeclName();
11708*67e74705SXin Li
11709*67e74705SXin Li // Check the first parameter type is not dependent.
11710*67e74705SXin Li QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11711*67e74705SXin Li if (FirstParamType->isDependentType())
11712*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11713*67e74705SXin Li << FnDecl->getDeclName() << ExpectedFirstParamType;
11714*67e74705SXin Li
11715*67e74705SXin Li // Check that the first parameter type is what we expect.
11716*67e74705SXin Li if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11717*67e74705SXin Li ExpectedFirstParamType)
11718*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11719*67e74705SXin Li << FnDecl->getDeclName() << ExpectedFirstParamType;
11720*67e74705SXin Li
11721*67e74705SXin Li return false;
11722*67e74705SXin Li }
11723*67e74705SXin Li
11724*67e74705SXin Li static bool
CheckOperatorNewDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)11725*67e74705SXin Li CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11726*67e74705SXin Li // C++ [basic.stc.dynamic.allocation]p1:
11727*67e74705SXin Li // A program is ill-formed if an allocation function is declared in a
11728*67e74705SXin Li // namespace scope other than global scope or declared static in global
11729*67e74705SXin Li // scope.
11730*67e74705SXin Li if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11731*67e74705SXin Li return true;
11732*67e74705SXin Li
11733*67e74705SXin Li CanQualType SizeTy =
11734*67e74705SXin Li SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11735*67e74705SXin Li
11736*67e74705SXin Li // C++ [basic.stc.dynamic.allocation]p1:
11737*67e74705SXin Li // The return type shall be void*. The first parameter shall have type
11738*67e74705SXin Li // std::size_t.
11739*67e74705SXin Li if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11740*67e74705SXin Li SizeTy,
11741*67e74705SXin Li diag::err_operator_new_dependent_param_type,
11742*67e74705SXin Li diag::err_operator_new_param_type))
11743*67e74705SXin Li return true;
11744*67e74705SXin Li
11745*67e74705SXin Li // C++ [basic.stc.dynamic.allocation]p1:
11746*67e74705SXin Li // The first parameter shall not have an associated default argument.
11747*67e74705SXin Li if (FnDecl->getParamDecl(0)->hasDefaultArg())
11748*67e74705SXin Li return SemaRef.Diag(FnDecl->getLocation(),
11749*67e74705SXin Li diag::err_operator_new_default_arg)
11750*67e74705SXin Li << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11751*67e74705SXin Li
11752*67e74705SXin Li return false;
11753*67e74705SXin Li }
11754*67e74705SXin Li
11755*67e74705SXin Li static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,FunctionDecl * FnDecl)11756*67e74705SXin Li CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11757*67e74705SXin Li // C++ [basic.stc.dynamic.deallocation]p1:
11758*67e74705SXin Li // A program is ill-formed if deallocation functions are declared in a
11759*67e74705SXin Li // namespace scope other than global scope or declared static in global
11760*67e74705SXin Li // scope.
11761*67e74705SXin Li if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11762*67e74705SXin Li return true;
11763*67e74705SXin Li
11764*67e74705SXin Li // C++ [basic.stc.dynamic.deallocation]p2:
11765*67e74705SXin Li // Each deallocation function shall return void and its first parameter
11766*67e74705SXin Li // shall be void*.
11767*67e74705SXin Li if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11768*67e74705SXin Li SemaRef.Context.VoidPtrTy,
11769*67e74705SXin Li diag::err_operator_delete_dependent_param_type,
11770*67e74705SXin Li diag::err_operator_delete_param_type))
11771*67e74705SXin Li return true;
11772*67e74705SXin Li
11773*67e74705SXin Li return false;
11774*67e74705SXin Li }
11775*67e74705SXin Li
11776*67e74705SXin Li /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11777*67e74705SXin Li /// of this overloaded operator is well-formed. If so, returns false;
11778*67e74705SXin Li /// otherwise, emits appropriate diagnostics and returns true.
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)11779*67e74705SXin Li bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11780*67e74705SXin Li assert(FnDecl && FnDecl->isOverloadedOperator() &&
11781*67e74705SXin Li "Expected an overloaded operator declaration");
11782*67e74705SXin Li
11783*67e74705SXin Li OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11784*67e74705SXin Li
11785*67e74705SXin Li // C++ [over.oper]p5:
11786*67e74705SXin Li // The allocation and deallocation functions, operator new,
11787*67e74705SXin Li // operator new[], operator delete and operator delete[], are
11788*67e74705SXin Li // described completely in 3.7.3. The attributes and restrictions
11789*67e74705SXin Li // found in the rest of this subclause do not apply to them unless
11790*67e74705SXin Li // explicitly stated in 3.7.3.
11791*67e74705SXin Li if (Op == OO_Delete || Op == OO_Array_Delete)
11792*67e74705SXin Li return CheckOperatorDeleteDeclaration(*this, FnDecl);
11793*67e74705SXin Li
11794*67e74705SXin Li if (Op == OO_New || Op == OO_Array_New)
11795*67e74705SXin Li return CheckOperatorNewDeclaration(*this, FnDecl);
11796*67e74705SXin Li
11797*67e74705SXin Li // C++ [over.oper]p6:
11798*67e74705SXin Li // An operator function shall either be a non-static member
11799*67e74705SXin Li // function or be a non-member function and have at least one
11800*67e74705SXin Li // parameter whose type is a class, a reference to a class, an
11801*67e74705SXin Li // enumeration, or a reference to an enumeration.
11802*67e74705SXin Li if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11803*67e74705SXin Li if (MethodDecl->isStatic())
11804*67e74705SXin Li return Diag(FnDecl->getLocation(),
11805*67e74705SXin Li diag::err_operator_overload_static) << FnDecl->getDeclName();
11806*67e74705SXin Li } else {
11807*67e74705SXin Li bool ClassOrEnumParam = false;
11808*67e74705SXin Li for (auto Param : FnDecl->parameters()) {
11809*67e74705SXin Li QualType ParamType = Param->getType().getNonReferenceType();
11810*67e74705SXin Li if (ParamType->isDependentType() || ParamType->isRecordType() ||
11811*67e74705SXin Li ParamType->isEnumeralType()) {
11812*67e74705SXin Li ClassOrEnumParam = true;
11813*67e74705SXin Li break;
11814*67e74705SXin Li }
11815*67e74705SXin Li }
11816*67e74705SXin Li
11817*67e74705SXin Li if (!ClassOrEnumParam)
11818*67e74705SXin Li return Diag(FnDecl->getLocation(),
11819*67e74705SXin Li diag::err_operator_overload_needs_class_or_enum)
11820*67e74705SXin Li << FnDecl->getDeclName();
11821*67e74705SXin Li }
11822*67e74705SXin Li
11823*67e74705SXin Li // C++ [over.oper]p8:
11824*67e74705SXin Li // An operator function cannot have default arguments (8.3.6),
11825*67e74705SXin Li // except where explicitly stated below.
11826*67e74705SXin Li //
11827*67e74705SXin Li // Only the function-call operator allows default arguments
11828*67e74705SXin Li // (C++ [over.call]p1).
11829*67e74705SXin Li if (Op != OO_Call) {
11830*67e74705SXin Li for (auto Param : FnDecl->parameters()) {
11831*67e74705SXin Li if (Param->hasDefaultArg())
11832*67e74705SXin Li return Diag(Param->getLocation(),
11833*67e74705SXin Li diag::err_operator_overload_default_arg)
11834*67e74705SXin Li << FnDecl->getDeclName() << Param->getDefaultArgRange();
11835*67e74705SXin Li }
11836*67e74705SXin Li }
11837*67e74705SXin Li
11838*67e74705SXin Li static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11839*67e74705SXin Li { false, false, false }
11840*67e74705SXin Li #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11841*67e74705SXin Li , { Unary, Binary, MemberOnly }
11842*67e74705SXin Li #include "clang/Basic/OperatorKinds.def"
11843*67e74705SXin Li };
11844*67e74705SXin Li
11845*67e74705SXin Li bool CanBeUnaryOperator = OperatorUses[Op][0];
11846*67e74705SXin Li bool CanBeBinaryOperator = OperatorUses[Op][1];
11847*67e74705SXin Li bool MustBeMemberOperator = OperatorUses[Op][2];
11848*67e74705SXin Li
11849*67e74705SXin Li // C++ [over.oper]p8:
11850*67e74705SXin Li // [...] Operator functions cannot have more or fewer parameters
11851*67e74705SXin Li // than the number required for the corresponding operator, as
11852*67e74705SXin Li // described in the rest of this subclause.
11853*67e74705SXin Li unsigned NumParams = FnDecl->getNumParams()
11854*67e74705SXin Li + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11855*67e74705SXin Li if (Op != OO_Call &&
11856*67e74705SXin Li ((NumParams == 1 && !CanBeUnaryOperator) ||
11857*67e74705SXin Li (NumParams == 2 && !CanBeBinaryOperator) ||
11858*67e74705SXin Li (NumParams < 1) || (NumParams > 2))) {
11859*67e74705SXin Li // We have the wrong number of parameters.
11860*67e74705SXin Li unsigned ErrorKind;
11861*67e74705SXin Li if (CanBeUnaryOperator && CanBeBinaryOperator) {
11862*67e74705SXin Li ErrorKind = 2; // 2 -> unary or binary.
11863*67e74705SXin Li } else if (CanBeUnaryOperator) {
11864*67e74705SXin Li ErrorKind = 0; // 0 -> unary
11865*67e74705SXin Li } else {
11866*67e74705SXin Li assert(CanBeBinaryOperator &&
11867*67e74705SXin Li "All non-call overloaded operators are unary or binary!");
11868*67e74705SXin Li ErrorKind = 1; // 1 -> binary
11869*67e74705SXin Li }
11870*67e74705SXin Li
11871*67e74705SXin Li return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11872*67e74705SXin Li << FnDecl->getDeclName() << NumParams << ErrorKind;
11873*67e74705SXin Li }
11874*67e74705SXin Li
11875*67e74705SXin Li // Overloaded operators other than operator() cannot be variadic.
11876*67e74705SXin Li if (Op != OO_Call &&
11877*67e74705SXin Li FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11878*67e74705SXin Li return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11879*67e74705SXin Li << FnDecl->getDeclName();
11880*67e74705SXin Li }
11881*67e74705SXin Li
11882*67e74705SXin Li // Some operators must be non-static member functions.
11883*67e74705SXin Li if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11884*67e74705SXin Li return Diag(FnDecl->getLocation(),
11885*67e74705SXin Li diag::err_operator_overload_must_be_member)
11886*67e74705SXin Li << FnDecl->getDeclName();
11887*67e74705SXin Li }
11888*67e74705SXin Li
11889*67e74705SXin Li // C++ [over.inc]p1:
11890*67e74705SXin Li // The user-defined function called operator++ implements the
11891*67e74705SXin Li // prefix and postfix ++ operator. If this function is a member
11892*67e74705SXin Li // function with no parameters, or a non-member function with one
11893*67e74705SXin Li // parameter of class or enumeration type, it defines the prefix
11894*67e74705SXin Li // increment operator ++ for objects of that type. If the function
11895*67e74705SXin Li // is a member function with one parameter (which shall be of type
11896*67e74705SXin Li // int) or a non-member function with two parameters (the second
11897*67e74705SXin Li // of which shall be of type int), it defines the postfix
11898*67e74705SXin Li // increment operator ++ for objects of that type.
11899*67e74705SXin Li if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11900*67e74705SXin Li ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11901*67e74705SXin Li QualType ParamType = LastParam->getType();
11902*67e74705SXin Li
11903*67e74705SXin Li if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11904*67e74705SXin Li !ParamType->isDependentType())
11905*67e74705SXin Li return Diag(LastParam->getLocation(),
11906*67e74705SXin Li diag::err_operator_overload_post_incdec_must_be_int)
11907*67e74705SXin Li << LastParam->getType() << (Op == OO_MinusMinus);
11908*67e74705SXin Li }
11909*67e74705SXin Li
11910*67e74705SXin Li return false;
11911*67e74705SXin Li }
11912*67e74705SXin Li
11913*67e74705SXin Li static bool
checkLiteralOperatorTemplateParameterList(Sema & SemaRef,FunctionTemplateDecl * TpDecl)11914*67e74705SXin Li checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
11915*67e74705SXin Li FunctionTemplateDecl *TpDecl) {
11916*67e74705SXin Li TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
11917*67e74705SXin Li
11918*67e74705SXin Li // Must have one or two template parameters.
11919*67e74705SXin Li if (TemplateParams->size() == 1) {
11920*67e74705SXin Li NonTypeTemplateParmDecl *PmDecl =
11921*67e74705SXin Li dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
11922*67e74705SXin Li
11923*67e74705SXin Li // The template parameter must be a char parameter pack.
11924*67e74705SXin Li if (PmDecl && PmDecl->isTemplateParameterPack() &&
11925*67e74705SXin Li SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
11926*67e74705SXin Li return false;
11927*67e74705SXin Li
11928*67e74705SXin Li } else if (TemplateParams->size() == 2) {
11929*67e74705SXin Li TemplateTypeParmDecl *PmType =
11930*67e74705SXin Li dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
11931*67e74705SXin Li NonTypeTemplateParmDecl *PmArgs =
11932*67e74705SXin Li dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
11933*67e74705SXin Li
11934*67e74705SXin Li // The second template parameter must be a parameter pack with the
11935*67e74705SXin Li // first template parameter as its type.
11936*67e74705SXin Li if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
11937*67e74705SXin Li PmArgs->isTemplateParameterPack()) {
11938*67e74705SXin Li const TemplateTypeParmType *TArgs =
11939*67e74705SXin Li PmArgs->getType()->getAs<TemplateTypeParmType>();
11940*67e74705SXin Li if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11941*67e74705SXin Li TArgs->getIndex() == PmType->getIndex()) {
11942*67e74705SXin Li if (SemaRef.ActiveTemplateInstantiations.empty())
11943*67e74705SXin Li SemaRef.Diag(TpDecl->getLocation(),
11944*67e74705SXin Li diag::ext_string_literal_operator_template);
11945*67e74705SXin Li return false;
11946*67e74705SXin Li }
11947*67e74705SXin Li }
11948*67e74705SXin Li }
11949*67e74705SXin Li
11950*67e74705SXin Li SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
11951*67e74705SXin Li diag::err_literal_operator_template)
11952*67e74705SXin Li << TpDecl->getTemplateParameters()->getSourceRange();
11953*67e74705SXin Li return true;
11954*67e74705SXin Li }
11955*67e74705SXin Li
11956*67e74705SXin Li /// CheckLiteralOperatorDeclaration - Check whether the declaration
11957*67e74705SXin Li /// of this literal operator function is well-formed. If so, returns
11958*67e74705SXin Li /// false; otherwise, emits appropriate diagnostics and returns true.
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)11959*67e74705SXin Li bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11960*67e74705SXin Li if (isa<CXXMethodDecl>(FnDecl)) {
11961*67e74705SXin Li Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11962*67e74705SXin Li << FnDecl->getDeclName();
11963*67e74705SXin Li return true;
11964*67e74705SXin Li }
11965*67e74705SXin Li
11966*67e74705SXin Li if (FnDecl->isExternC()) {
11967*67e74705SXin Li Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11968*67e74705SXin Li return true;
11969*67e74705SXin Li }
11970*67e74705SXin Li
11971*67e74705SXin Li // This might be the definition of a literal operator template.
11972*67e74705SXin Li FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11973*67e74705SXin Li
11974*67e74705SXin Li // This might be a specialization of a literal operator template.
11975*67e74705SXin Li if (!TpDecl)
11976*67e74705SXin Li TpDecl = FnDecl->getPrimaryTemplate();
11977*67e74705SXin Li
11978*67e74705SXin Li // template <char...> type operator "" name() and
11979*67e74705SXin Li // template <class T, T...> type operator "" name() are the only valid
11980*67e74705SXin Li // template signatures, and the only valid signatures with no parameters.
11981*67e74705SXin Li if (TpDecl) {
11982*67e74705SXin Li if (FnDecl->param_size() != 0) {
11983*67e74705SXin Li Diag(FnDecl->getLocation(),
11984*67e74705SXin Li diag::err_literal_operator_template_with_params);
11985*67e74705SXin Li return true;
11986*67e74705SXin Li }
11987*67e74705SXin Li
11988*67e74705SXin Li if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
11989*67e74705SXin Li return true;
11990*67e74705SXin Li
11991*67e74705SXin Li } else if (FnDecl->param_size() == 1) {
11992*67e74705SXin Li const ParmVarDecl *Param = FnDecl->getParamDecl(0);
11993*67e74705SXin Li
11994*67e74705SXin Li QualType ParamType = Param->getType().getUnqualifiedType();
11995*67e74705SXin Li
11996*67e74705SXin Li // Only unsigned long long int, long double, any character type, and const
11997*67e74705SXin Li // char * are allowed as the only parameters.
11998*67e74705SXin Li if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
11999*67e74705SXin Li ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12000*67e74705SXin Li Context.hasSameType(ParamType, Context.CharTy) ||
12001*67e74705SXin Li Context.hasSameType(ParamType, Context.WideCharTy) ||
12002*67e74705SXin Li Context.hasSameType(ParamType, Context.Char16Ty) ||
12003*67e74705SXin Li Context.hasSameType(ParamType, Context.Char32Ty)) {
12004*67e74705SXin Li } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12005*67e74705SXin Li QualType InnerType = Ptr->getPointeeType();
12006*67e74705SXin Li
12007*67e74705SXin Li // Pointer parameter must be a const char *.
12008*67e74705SXin Li if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12009*67e74705SXin Li Context.CharTy) &&
12010*67e74705SXin Li InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12011*67e74705SXin Li Diag(Param->getSourceRange().getBegin(),
12012*67e74705SXin Li diag::err_literal_operator_param)
12013*67e74705SXin Li << ParamType << "'const char *'" << Param->getSourceRange();
12014*67e74705SXin Li return true;
12015*67e74705SXin Li }
12016*67e74705SXin Li
12017*67e74705SXin Li } else if (ParamType->isRealFloatingType()) {
12018*67e74705SXin Li Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12019*67e74705SXin Li << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12020*67e74705SXin Li return true;
12021*67e74705SXin Li
12022*67e74705SXin Li } else if (ParamType->isIntegerType()) {
12023*67e74705SXin Li Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12024*67e74705SXin Li << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12025*67e74705SXin Li return true;
12026*67e74705SXin Li
12027*67e74705SXin Li } else {
12028*67e74705SXin Li Diag(Param->getSourceRange().getBegin(),
12029*67e74705SXin Li diag::err_literal_operator_invalid_param)
12030*67e74705SXin Li << ParamType << Param->getSourceRange();
12031*67e74705SXin Li return true;
12032*67e74705SXin Li }
12033*67e74705SXin Li
12034*67e74705SXin Li } else if (FnDecl->param_size() == 2) {
12035*67e74705SXin Li FunctionDecl::param_iterator Param = FnDecl->param_begin();
12036*67e74705SXin Li
12037*67e74705SXin Li // First, verify that the first parameter is correct.
12038*67e74705SXin Li
12039*67e74705SXin Li QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12040*67e74705SXin Li
12041*67e74705SXin Li // Two parameter function must have a pointer to const as a
12042*67e74705SXin Li // first parameter; let's strip those qualifiers.
12043*67e74705SXin Li const PointerType *PT = FirstParamType->getAs<PointerType>();
12044*67e74705SXin Li
12045*67e74705SXin Li if (!PT) {
12046*67e74705SXin Li Diag((*Param)->getSourceRange().getBegin(),
12047*67e74705SXin Li diag::err_literal_operator_param)
12048*67e74705SXin Li << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12049*67e74705SXin Li return true;
12050*67e74705SXin Li }
12051*67e74705SXin Li
12052*67e74705SXin Li QualType PointeeType = PT->getPointeeType();
12053*67e74705SXin Li // First parameter must be const
12054*67e74705SXin Li if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12055*67e74705SXin Li Diag((*Param)->getSourceRange().getBegin(),
12056*67e74705SXin Li diag::err_literal_operator_param)
12057*67e74705SXin Li << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12058*67e74705SXin Li return true;
12059*67e74705SXin Li }
12060*67e74705SXin Li
12061*67e74705SXin Li QualType InnerType = PointeeType.getUnqualifiedType();
12062*67e74705SXin Li // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12063*67e74705SXin Li // are allowed as the first parameter to a two-parameter function
12064*67e74705SXin Li if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12065*67e74705SXin Li Context.hasSameType(InnerType, Context.WideCharTy) ||
12066*67e74705SXin Li Context.hasSameType(InnerType, Context.Char16Ty) ||
12067*67e74705SXin Li Context.hasSameType(InnerType, Context.Char32Ty))) {
12068*67e74705SXin Li Diag((*Param)->getSourceRange().getBegin(),
12069*67e74705SXin Li diag::err_literal_operator_param)
12070*67e74705SXin Li << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12071*67e74705SXin Li return true;
12072*67e74705SXin Li }
12073*67e74705SXin Li
12074*67e74705SXin Li // Move on to the second and final parameter.
12075*67e74705SXin Li ++Param;
12076*67e74705SXin Li
12077*67e74705SXin Li // The second parameter must be a std::size_t.
12078*67e74705SXin Li QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12079*67e74705SXin Li if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12080*67e74705SXin Li Diag((*Param)->getSourceRange().getBegin(),
12081*67e74705SXin Li diag::err_literal_operator_param)
12082*67e74705SXin Li << SecondParamType << Context.getSizeType()
12083*67e74705SXin Li << (*Param)->getSourceRange();
12084*67e74705SXin Li return true;
12085*67e74705SXin Li }
12086*67e74705SXin Li } else {
12087*67e74705SXin Li Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12088*67e74705SXin Li return true;
12089*67e74705SXin Li }
12090*67e74705SXin Li
12091*67e74705SXin Li // Parameters are good.
12092*67e74705SXin Li
12093*67e74705SXin Li // A parameter-declaration-clause containing a default argument is not
12094*67e74705SXin Li // equivalent to any of the permitted forms.
12095*67e74705SXin Li for (auto Param : FnDecl->parameters()) {
12096*67e74705SXin Li if (Param->hasDefaultArg()) {
12097*67e74705SXin Li Diag(Param->getDefaultArgRange().getBegin(),
12098*67e74705SXin Li diag::err_literal_operator_default_argument)
12099*67e74705SXin Li << Param->getDefaultArgRange();
12100*67e74705SXin Li break;
12101*67e74705SXin Li }
12102*67e74705SXin Li }
12103*67e74705SXin Li
12104*67e74705SXin Li StringRef LiteralName
12105*67e74705SXin Li = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12106*67e74705SXin Li if (LiteralName[0] != '_') {
12107*67e74705SXin Li // C++11 [usrlit.suffix]p1:
12108*67e74705SXin Li // Literal suffix identifiers that do not start with an underscore
12109*67e74705SXin Li // are reserved for future standardization.
12110*67e74705SXin Li Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12111*67e74705SXin Li << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12112*67e74705SXin Li }
12113*67e74705SXin Li
12114*67e74705SXin Li return false;
12115*67e74705SXin Li }
12116*67e74705SXin Li
12117*67e74705SXin Li /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12118*67e74705SXin Li /// linkage specification, including the language and (if present)
12119*67e74705SXin Li /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12120*67e74705SXin Li /// language string literal. LBraceLoc, if valid, provides the location of
12121*67e74705SXin Li /// the '{' brace. Otherwise, this linkage specification does not
12122*67e74705SXin Li /// have any braces.
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,Expr * LangStr,SourceLocation LBraceLoc)12123*67e74705SXin Li Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12124*67e74705SXin Li Expr *LangStr,
12125*67e74705SXin Li SourceLocation LBraceLoc) {
12126*67e74705SXin Li StringLiteral *Lit = cast<StringLiteral>(LangStr);
12127*67e74705SXin Li if (!Lit->isAscii()) {
12128*67e74705SXin Li Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12129*67e74705SXin Li << LangStr->getSourceRange();
12130*67e74705SXin Li return nullptr;
12131*67e74705SXin Li }
12132*67e74705SXin Li
12133*67e74705SXin Li StringRef Lang = Lit->getString();
12134*67e74705SXin Li LinkageSpecDecl::LanguageIDs Language;
12135*67e74705SXin Li if (Lang == "C")
12136*67e74705SXin Li Language = LinkageSpecDecl::lang_c;
12137*67e74705SXin Li else if (Lang == "C++")
12138*67e74705SXin Li Language = LinkageSpecDecl::lang_cxx;
12139*67e74705SXin Li else {
12140*67e74705SXin Li Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12141*67e74705SXin Li << LangStr->getSourceRange();
12142*67e74705SXin Li return nullptr;
12143*67e74705SXin Li }
12144*67e74705SXin Li
12145*67e74705SXin Li // FIXME: Add all the various semantics of linkage specifications
12146*67e74705SXin Li
12147*67e74705SXin Li LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12148*67e74705SXin Li LangStr->getExprLoc(), Language,
12149*67e74705SXin Li LBraceLoc.isValid());
12150*67e74705SXin Li CurContext->addDecl(D);
12151*67e74705SXin Li PushDeclContext(S, D);
12152*67e74705SXin Li return D;
12153*67e74705SXin Li }
12154*67e74705SXin Li
12155*67e74705SXin Li /// ActOnFinishLinkageSpecification - Complete the definition of
12156*67e74705SXin Li /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12157*67e74705SXin Li /// valid, it's the position of the closing '}' brace in a linkage
12158*67e74705SXin Li /// specification that uses braces.
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)12159*67e74705SXin Li Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12160*67e74705SXin Li Decl *LinkageSpec,
12161*67e74705SXin Li SourceLocation RBraceLoc) {
12162*67e74705SXin Li if (RBraceLoc.isValid()) {
12163*67e74705SXin Li LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12164*67e74705SXin Li LSDecl->setRBraceLoc(RBraceLoc);
12165*67e74705SXin Li }
12166*67e74705SXin Li PopDeclContext();
12167*67e74705SXin Li return LinkageSpec;
12168*67e74705SXin Li }
12169*67e74705SXin Li
ActOnEmptyDeclaration(Scope * S,AttributeList * AttrList,SourceLocation SemiLoc)12170*67e74705SXin Li Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12171*67e74705SXin Li AttributeList *AttrList,
12172*67e74705SXin Li SourceLocation SemiLoc) {
12173*67e74705SXin Li Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12174*67e74705SXin Li // Attribute declarations appertain to empty declaration so we handle
12175*67e74705SXin Li // them here.
12176*67e74705SXin Li if (AttrList)
12177*67e74705SXin Li ProcessDeclAttributeList(S, ED, AttrList);
12178*67e74705SXin Li
12179*67e74705SXin Li CurContext->addDecl(ED);
12180*67e74705SXin Li return ED;
12181*67e74705SXin Li }
12182*67e74705SXin Li
12183*67e74705SXin Li /// \brief Perform semantic analysis for the variable declaration that
12184*67e74705SXin Li /// occurs within a C++ catch clause, returning the newly-created
12185*67e74705SXin Li /// variable.
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,IdentifierInfo * Name)12186*67e74705SXin Li VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12187*67e74705SXin Li TypeSourceInfo *TInfo,
12188*67e74705SXin Li SourceLocation StartLoc,
12189*67e74705SXin Li SourceLocation Loc,
12190*67e74705SXin Li IdentifierInfo *Name) {
12191*67e74705SXin Li bool Invalid = false;
12192*67e74705SXin Li QualType ExDeclType = TInfo->getType();
12193*67e74705SXin Li
12194*67e74705SXin Li // Arrays and functions decay.
12195*67e74705SXin Li if (ExDeclType->isArrayType())
12196*67e74705SXin Li ExDeclType = Context.getArrayDecayedType(ExDeclType);
12197*67e74705SXin Li else if (ExDeclType->isFunctionType())
12198*67e74705SXin Li ExDeclType = Context.getPointerType(ExDeclType);
12199*67e74705SXin Li
12200*67e74705SXin Li // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12201*67e74705SXin Li // The exception-declaration shall not denote a pointer or reference to an
12202*67e74705SXin Li // incomplete type, other than [cv] void*.
12203*67e74705SXin Li // N2844 forbids rvalue references.
12204*67e74705SXin Li if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12205*67e74705SXin Li Diag(Loc, diag::err_catch_rvalue_ref);
12206*67e74705SXin Li Invalid = true;
12207*67e74705SXin Li }
12208*67e74705SXin Li
12209*67e74705SXin Li if (ExDeclType->isVariablyModifiedType()) {
12210*67e74705SXin Li Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
12211*67e74705SXin Li Invalid = true;
12212*67e74705SXin Li }
12213*67e74705SXin Li
12214*67e74705SXin Li QualType BaseType = ExDeclType;
12215*67e74705SXin Li int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12216*67e74705SXin Li unsigned DK = diag::err_catch_incomplete;
12217*67e74705SXin Li if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12218*67e74705SXin Li BaseType = Ptr->getPointeeType();
12219*67e74705SXin Li Mode = 1;
12220*67e74705SXin Li DK = diag::err_catch_incomplete_ptr;
12221*67e74705SXin Li } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12222*67e74705SXin Li // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12223*67e74705SXin Li BaseType = Ref->getPointeeType();
12224*67e74705SXin Li Mode = 2;
12225*67e74705SXin Li DK = diag::err_catch_incomplete_ref;
12226*67e74705SXin Li }
12227*67e74705SXin Li if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12228*67e74705SXin Li !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12229*67e74705SXin Li Invalid = true;
12230*67e74705SXin Li
12231*67e74705SXin Li if (!Invalid && !ExDeclType->isDependentType() &&
12232*67e74705SXin Li RequireNonAbstractType(Loc, ExDeclType,
12233*67e74705SXin Li diag::err_abstract_type_in_decl,
12234*67e74705SXin Li AbstractVariableType))
12235*67e74705SXin Li Invalid = true;
12236*67e74705SXin Li
12237*67e74705SXin Li // Only the non-fragile NeXT runtime currently supports C++ catches
12238*67e74705SXin Li // of ObjC types, and no runtime supports catching ObjC types by value.
12239*67e74705SXin Li if (!Invalid && getLangOpts().ObjC1) {
12240*67e74705SXin Li QualType T = ExDeclType;
12241*67e74705SXin Li if (const ReferenceType *RT = T->getAs<ReferenceType>())
12242*67e74705SXin Li T = RT->getPointeeType();
12243*67e74705SXin Li
12244*67e74705SXin Li if (T->isObjCObjectType()) {
12245*67e74705SXin Li Diag(Loc, diag::err_objc_object_catch);
12246*67e74705SXin Li Invalid = true;
12247*67e74705SXin Li } else if (T->isObjCObjectPointerType()) {
12248*67e74705SXin Li // FIXME: should this be a test for macosx-fragile specifically?
12249*67e74705SXin Li if (getLangOpts().ObjCRuntime.isFragile())
12250*67e74705SXin Li Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12251*67e74705SXin Li }
12252*67e74705SXin Li }
12253*67e74705SXin Li
12254*67e74705SXin Li VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12255*67e74705SXin Li ExDeclType, TInfo, SC_None);
12256*67e74705SXin Li ExDecl->setExceptionVariable(true);
12257*67e74705SXin Li
12258*67e74705SXin Li // In ARC, infer 'retaining' for variables of retainable type.
12259*67e74705SXin Li if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12260*67e74705SXin Li Invalid = true;
12261*67e74705SXin Li
12262*67e74705SXin Li if (!Invalid && !ExDeclType->isDependentType()) {
12263*67e74705SXin Li if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12264*67e74705SXin Li // Insulate this from anything else we might currently be parsing.
12265*67e74705SXin Li EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12266*67e74705SXin Li
12267*67e74705SXin Li // C++ [except.handle]p16:
12268*67e74705SXin Li // The object declared in an exception-declaration or, if the
12269*67e74705SXin Li // exception-declaration does not specify a name, a temporary (12.2) is
12270*67e74705SXin Li // copy-initialized (8.5) from the exception object. [...]
12271*67e74705SXin Li // The object is destroyed when the handler exits, after the destruction
12272*67e74705SXin Li // of any automatic objects initialized within the handler.
12273*67e74705SXin Li //
12274*67e74705SXin Li // We just pretend to initialize the object with itself, then make sure
12275*67e74705SXin Li // it can be destroyed later.
12276*67e74705SXin Li QualType initType = Context.getExceptionObjectType(ExDeclType);
12277*67e74705SXin Li
12278*67e74705SXin Li InitializedEntity entity =
12279*67e74705SXin Li InitializedEntity::InitializeVariable(ExDecl);
12280*67e74705SXin Li InitializationKind initKind =
12281*67e74705SXin Li InitializationKind::CreateCopy(Loc, SourceLocation());
12282*67e74705SXin Li
12283*67e74705SXin Li Expr *opaqueValue =
12284*67e74705SXin Li new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12285*67e74705SXin Li InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12286*67e74705SXin Li ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12287*67e74705SXin Li if (result.isInvalid())
12288*67e74705SXin Li Invalid = true;
12289*67e74705SXin Li else {
12290*67e74705SXin Li // If the constructor used was non-trivial, set this as the
12291*67e74705SXin Li // "initializer".
12292*67e74705SXin Li CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12293*67e74705SXin Li if (!construct->getConstructor()->isTrivial()) {
12294*67e74705SXin Li Expr *init = MaybeCreateExprWithCleanups(construct);
12295*67e74705SXin Li ExDecl->setInit(init);
12296*67e74705SXin Li }
12297*67e74705SXin Li
12298*67e74705SXin Li // And make sure it's destructable.
12299*67e74705SXin Li FinalizeVarWithDestructor(ExDecl, recordType);
12300*67e74705SXin Li }
12301*67e74705SXin Li }
12302*67e74705SXin Li }
12303*67e74705SXin Li
12304*67e74705SXin Li if (Invalid)
12305*67e74705SXin Li ExDecl->setInvalidDecl();
12306*67e74705SXin Li
12307*67e74705SXin Li return ExDecl;
12308*67e74705SXin Li }
12309*67e74705SXin Li
12310*67e74705SXin Li /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12311*67e74705SXin Li /// handler.
ActOnExceptionDeclarator(Scope * S,Declarator & D)12312*67e74705SXin Li Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12313*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12314*67e74705SXin Li bool Invalid = D.isInvalidType();
12315*67e74705SXin Li
12316*67e74705SXin Li // Check for unexpanded parameter packs.
12317*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12318*67e74705SXin Li UPPC_ExceptionType)) {
12319*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12320*67e74705SXin Li D.getIdentifierLoc());
12321*67e74705SXin Li Invalid = true;
12322*67e74705SXin Li }
12323*67e74705SXin Li
12324*67e74705SXin Li IdentifierInfo *II = D.getIdentifier();
12325*67e74705SXin Li if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12326*67e74705SXin Li LookupOrdinaryName,
12327*67e74705SXin Li ForRedeclaration)) {
12328*67e74705SXin Li // The scope should be freshly made just for us. There is just no way
12329*67e74705SXin Li // it contains any previous declaration, except for function parameters in
12330*67e74705SXin Li // a function-try-block's catch statement.
12331*67e74705SXin Li assert(!S->isDeclScope(PrevDecl));
12332*67e74705SXin Li if (isDeclInScope(PrevDecl, CurContext, S)) {
12333*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_redefinition)
12334*67e74705SXin Li << D.getIdentifier();
12335*67e74705SXin Li Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12336*67e74705SXin Li Invalid = true;
12337*67e74705SXin Li } else if (PrevDecl->isTemplateParameter())
12338*67e74705SXin Li // Maybe we will complain about the shadowed template parameter.
12339*67e74705SXin Li DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12340*67e74705SXin Li }
12341*67e74705SXin Li
12342*67e74705SXin Li if (D.getCXXScopeSpec().isSet() && !Invalid) {
12343*67e74705SXin Li Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12344*67e74705SXin Li << D.getCXXScopeSpec().getRange();
12345*67e74705SXin Li Invalid = true;
12346*67e74705SXin Li }
12347*67e74705SXin Li
12348*67e74705SXin Li VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12349*67e74705SXin Li D.getLocStart(),
12350*67e74705SXin Li D.getIdentifierLoc(),
12351*67e74705SXin Li D.getIdentifier());
12352*67e74705SXin Li if (Invalid)
12353*67e74705SXin Li ExDecl->setInvalidDecl();
12354*67e74705SXin Li
12355*67e74705SXin Li // Add the exception declaration into this scope.
12356*67e74705SXin Li if (II)
12357*67e74705SXin Li PushOnScopeChains(ExDecl, S);
12358*67e74705SXin Li else
12359*67e74705SXin Li CurContext->addDecl(ExDecl);
12360*67e74705SXin Li
12361*67e74705SXin Li ProcessDeclAttributes(S, ExDecl, D);
12362*67e74705SXin Li return ExDecl;
12363*67e74705SXin Li }
12364*67e74705SXin Li
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr,SourceLocation RParenLoc)12365*67e74705SXin Li Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12366*67e74705SXin Li Expr *AssertExpr,
12367*67e74705SXin Li Expr *AssertMessageExpr,
12368*67e74705SXin Li SourceLocation RParenLoc) {
12369*67e74705SXin Li StringLiteral *AssertMessage =
12370*67e74705SXin Li AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12371*67e74705SXin Li
12372*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12373*67e74705SXin Li return nullptr;
12374*67e74705SXin Li
12375*67e74705SXin Li return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12376*67e74705SXin Li AssertMessage, RParenLoc, false);
12377*67e74705SXin Li }
12378*67e74705SXin Li
BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,StringLiteral * AssertMessage,SourceLocation RParenLoc,bool Failed)12379*67e74705SXin Li Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12380*67e74705SXin Li Expr *AssertExpr,
12381*67e74705SXin Li StringLiteral *AssertMessage,
12382*67e74705SXin Li SourceLocation RParenLoc,
12383*67e74705SXin Li bool Failed) {
12384*67e74705SXin Li assert(AssertExpr != nullptr && "Expected non-null condition");
12385*67e74705SXin Li if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12386*67e74705SXin Li !Failed) {
12387*67e74705SXin Li // In a static_assert-declaration, the constant-expression shall be a
12388*67e74705SXin Li // constant expression that can be contextually converted to bool.
12389*67e74705SXin Li ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12390*67e74705SXin Li if (Converted.isInvalid())
12391*67e74705SXin Li Failed = true;
12392*67e74705SXin Li
12393*67e74705SXin Li llvm::APSInt Cond;
12394*67e74705SXin Li if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12395*67e74705SXin Li diag::err_static_assert_expression_is_not_constant,
12396*67e74705SXin Li /*AllowFold=*/false).isInvalid())
12397*67e74705SXin Li Failed = true;
12398*67e74705SXin Li
12399*67e74705SXin Li if (!Failed && !Cond) {
12400*67e74705SXin Li SmallString<256> MsgBuffer;
12401*67e74705SXin Li llvm::raw_svector_ostream Msg(MsgBuffer);
12402*67e74705SXin Li if (AssertMessage)
12403*67e74705SXin Li AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12404*67e74705SXin Li Diag(StaticAssertLoc, diag::err_static_assert_failed)
12405*67e74705SXin Li << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12406*67e74705SXin Li Failed = true;
12407*67e74705SXin Li }
12408*67e74705SXin Li }
12409*67e74705SXin Li
12410*67e74705SXin Li Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12411*67e74705SXin Li AssertExpr, AssertMessage, RParenLoc,
12412*67e74705SXin Li Failed);
12413*67e74705SXin Li
12414*67e74705SXin Li CurContext->addDecl(Decl);
12415*67e74705SXin Li return Decl;
12416*67e74705SXin Li }
12417*67e74705SXin Li
12418*67e74705SXin Li /// \brief Perform semantic analysis of the given friend type declaration.
12419*67e74705SXin Li ///
12420*67e74705SXin Li /// \returns A friend declaration that.
CheckFriendTypeDecl(SourceLocation LocStart,SourceLocation FriendLoc,TypeSourceInfo * TSInfo)12421*67e74705SXin Li FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12422*67e74705SXin Li SourceLocation FriendLoc,
12423*67e74705SXin Li TypeSourceInfo *TSInfo) {
12424*67e74705SXin Li assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12425*67e74705SXin Li
12426*67e74705SXin Li QualType T = TSInfo->getType();
12427*67e74705SXin Li SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12428*67e74705SXin Li
12429*67e74705SXin Li // C++03 [class.friend]p2:
12430*67e74705SXin Li // An elaborated-type-specifier shall be used in a friend declaration
12431*67e74705SXin Li // for a class.*
12432*67e74705SXin Li //
12433*67e74705SXin Li // * The class-key of the elaborated-type-specifier is required.
12434*67e74705SXin Li if (!ActiveTemplateInstantiations.empty()) {
12435*67e74705SXin Li // Do not complain about the form of friend template types during
12436*67e74705SXin Li // template instantiation; we will already have complained when the
12437*67e74705SXin Li // template was declared.
12438*67e74705SXin Li } else {
12439*67e74705SXin Li if (!T->isElaboratedTypeSpecifier()) {
12440*67e74705SXin Li // If we evaluated the type to a record type, suggest putting
12441*67e74705SXin Li // a tag in front.
12442*67e74705SXin Li if (const RecordType *RT = T->getAs<RecordType>()) {
12443*67e74705SXin Li RecordDecl *RD = RT->getDecl();
12444*67e74705SXin Li
12445*67e74705SXin Li SmallString<16> InsertionText(" ");
12446*67e74705SXin Li InsertionText += RD->getKindName();
12447*67e74705SXin Li
12448*67e74705SXin Li Diag(TypeRange.getBegin(),
12449*67e74705SXin Li getLangOpts().CPlusPlus11 ?
12450*67e74705SXin Li diag::warn_cxx98_compat_unelaborated_friend_type :
12451*67e74705SXin Li diag::ext_unelaborated_friend_type)
12452*67e74705SXin Li << (unsigned) RD->getTagKind()
12453*67e74705SXin Li << T
12454*67e74705SXin Li << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
12455*67e74705SXin Li InsertionText);
12456*67e74705SXin Li } else {
12457*67e74705SXin Li Diag(FriendLoc,
12458*67e74705SXin Li getLangOpts().CPlusPlus11 ?
12459*67e74705SXin Li diag::warn_cxx98_compat_nonclass_type_friend :
12460*67e74705SXin Li diag::ext_nonclass_type_friend)
12461*67e74705SXin Li << T
12462*67e74705SXin Li << TypeRange;
12463*67e74705SXin Li }
12464*67e74705SXin Li } else if (T->getAs<EnumType>()) {
12465*67e74705SXin Li Diag(FriendLoc,
12466*67e74705SXin Li getLangOpts().CPlusPlus11 ?
12467*67e74705SXin Li diag::warn_cxx98_compat_enum_friend :
12468*67e74705SXin Li diag::ext_enum_friend)
12469*67e74705SXin Li << T
12470*67e74705SXin Li << TypeRange;
12471*67e74705SXin Li }
12472*67e74705SXin Li
12473*67e74705SXin Li // C++11 [class.friend]p3:
12474*67e74705SXin Li // A friend declaration that does not declare a function shall have one
12475*67e74705SXin Li // of the following forms:
12476*67e74705SXin Li // friend elaborated-type-specifier ;
12477*67e74705SXin Li // friend simple-type-specifier ;
12478*67e74705SXin Li // friend typename-specifier ;
12479*67e74705SXin Li if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12480*67e74705SXin Li Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12481*67e74705SXin Li }
12482*67e74705SXin Li
12483*67e74705SXin Li // If the type specifier in a friend declaration designates a (possibly
12484*67e74705SXin Li // cv-qualified) class type, that class is declared as a friend; otherwise,
12485*67e74705SXin Li // the friend declaration is ignored.
12486*67e74705SXin Li return FriendDecl::Create(Context, CurContext,
12487*67e74705SXin Li TSInfo->getTypeLoc().getLocStart(), TSInfo,
12488*67e74705SXin Li FriendLoc);
12489*67e74705SXin Li }
12490*67e74705SXin Li
12491*67e74705SXin Li /// Handle a friend tag declaration where the scope specifier was
12492*67e74705SXin Li /// templated.
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,MultiTemplateParamsArg TempParamLists)12493*67e74705SXin Li Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12494*67e74705SXin Li unsigned TagSpec, SourceLocation TagLoc,
12495*67e74705SXin Li CXXScopeSpec &SS,
12496*67e74705SXin Li IdentifierInfo *Name,
12497*67e74705SXin Li SourceLocation NameLoc,
12498*67e74705SXin Li AttributeList *Attr,
12499*67e74705SXin Li MultiTemplateParamsArg TempParamLists) {
12500*67e74705SXin Li TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12501*67e74705SXin Li
12502*67e74705SXin Li bool isExplicitSpecialization = false;
12503*67e74705SXin Li bool Invalid = false;
12504*67e74705SXin Li
12505*67e74705SXin Li if (TemplateParameterList *TemplateParams =
12506*67e74705SXin Li MatchTemplateParametersToScopeSpecifier(
12507*67e74705SXin Li TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12508*67e74705SXin Li isExplicitSpecialization, Invalid)) {
12509*67e74705SXin Li if (TemplateParams->size() > 0) {
12510*67e74705SXin Li // This is a declaration of a class template.
12511*67e74705SXin Li if (Invalid)
12512*67e74705SXin Li return nullptr;
12513*67e74705SXin Li
12514*67e74705SXin Li return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12515*67e74705SXin Li NameLoc, Attr, TemplateParams, AS_public,
12516*67e74705SXin Li /*ModulePrivateLoc=*/SourceLocation(),
12517*67e74705SXin Li FriendLoc, TempParamLists.size() - 1,
12518*67e74705SXin Li TempParamLists.data()).get();
12519*67e74705SXin Li } else {
12520*67e74705SXin Li // The "template<>" header is extraneous.
12521*67e74705SXin Li Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12522*67e74705SXin Li << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12523*67e74705SXin Li isExplicitSpecialization = true;
12524*67e74705SXin Li }
12525*67e74705SXin Li }
12526*67e74705SXin Li
12527*67e74705SXin Li if (Invalid) return nullptr;
12528*67e74705SXin Li
12529*67e74705SXin Li bool isAllExplicitSpecializations = true;
12530*67e74705SXin Li for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12531*67e74705SXin Li if (TempParamLists[I]->size()) {
12532*67e74705SXin Li isAllExplicitSpecializations = false;
12533*67e74705SXin Li break;
12534*67e74705SXin Li }
12535*67e74705SXin Li }
12536*67e74705SXin Li
12537*67e74705SXin Li // FIXME: don't ignore attributes.
12538*67e74705SXin Li
12539*67e74705SXin Li // If it's explicit specializations all the way down, just forget
12540*67e74705SXin Li // about the template header and build an appropriate non-templated
12541*67e74705SXin Li // friend. TODO: for source fidelity, remember the headers.
12542*67e74705SXin Li if (isAllExplicitSpecializations) {
12543*67e74705SXin Li if (SS.isEmpty()) {
12544*67e74705SXin Li bool Owned = false;
12545*67e74705SXin Li bool IsDependent = false;
12546*67e74705SXin Li return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12547*67e74705SXin Li Attr, AS_public,
12548*67e74705SXin Li /*ModulePrivateLoc=*/SourceLocation(),
12549*67e74705SXin Li MultiTemplateParamsArg(), Owned, IsDependent,
12550*67e74705SXin Li /*ScopedEnumKWLoc=*/SourceLocation(),
12551*67e74705SXin Li /*ScopedEnumUsesClassTag=*/false,
12552*67e74705SXin Li /*UnderlyingType=*/TypeResult(),
12553*67e74705SXin Li /*IsTypeSpecifier=*/false);
12554*67e74705SXin Li }
12555*67e74705SXin Li
12556*67e74705SXin Li NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12557*67e74705SXin Li ElaboratedTypeKeyword Keyword
12558*67e74705SXin Li = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12559*67e74705SXin Li QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12560*67e74705SXin Li *Name, NameLoc);
12561*67e74705SXin Li if (T.isNull())
12562*67e74705SXin Li return nullptr;
12563*67e74705SXin Li
12564*67e74705SXin Li TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12565*67e74705SXin Li if (isa<DependentNameType>(T)) {
12566*67e74705SXin Li DependentNameTypeLoc TL =
12567*67e74705SXin Li TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12568*67e74705SXin Li TL.setElaboratedKeywordLoc(TagLoc);
12569*67e74705SXin Li TL.setQualifierLoc(QualifierLoc);
12570*67e74705SXin Li TL.setNameLoc(NameLoc);
12571*67e74705SXin Li } else {
12572*67e74705SXin Li ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12573*67e74705SXin Li TL.setElaboratedKeywordLoc(TagLoc);
12574*67e74705SXin Li TL.setQualifierLoc(QualifierLoc);
12575*67e74705SXin Li TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12576*67e74705SXin Li }
12577*67e74705SXin Li
12578*67e74705SXin Li FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12579*67e74705SXin Li TSI, FriendLoc, TempParamLists);
12580*67e74705SXin Li Friend->setAccess(AS_public);
12581*67e74705SXin Li CurContext->addDecl(Friend);
12582*67e74705SXin Li return Friend;
12583*67e74705SXin Li }
12584*67e74705SXin Li
12585*67e74705SXin Li assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12586*67e74705SXin Li
12587*67e74705SXin Li
12588*67e74705SXin Li
12589*67e74705SXin Li // Handle the case of a templated-scope friend class. e.g.
12590*67e74705SXin Li // template <class T> class A<T>::B;
12591*67e74705SXin Li // FIXME: we don't support these right now.
12592*67e74705SXin Li Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12593*67e74705SXin Li << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12594*67e74705SXin Li ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12595*67e74705SXin Li QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12596*67e74705SXin Li TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12597*67e74705SXin Li DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12598*67e74705SXin Li TL.setElaboratedKeywordLoc(TagLoc);
12599*67e74705SXin Li TL.setQualifierLoc(SS.getWithLocInContext(Context));
12600*67e74705SXin Li TL.setNameLoc(NameLoc);
12601*67e74705SXin Li
12602*67e74705SXin Li FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12603*67e74705SXin Li TSI, FriendLoc, TempParamLists);
12604*67e74705SXin Li Friend->setAccess(AS_public);
12605*67e74705SXin Li Friend->setUnsupportedFriend(true);
12606*67e74705SXin Li CurContext->addDecl(Friend);
12607*67e74705SXin Li return Friend;
12608*67e74705SXin Li }
12609*67e74705SXin Li
12610*67e74705SXin Li
12611*67e74705SXin Li /// Handle a friend type declaration. This works in tandem with
12612*67e74705SXin Li /// ActOnTag.
12613*67e74705SXin Li ///
12614*67e74705SXin Li /// Notes on friend class templates:
12615*67e74705SXin Li ///
12616*67e74705SXin Li /// We generally treat friend class declarations as if they were
12617*67e74705SXin Li /// declaring a class. So, for example, the elaborated type specifier
12618*67e74705SXin Li /// in a friend declaration is required to obey the restrictions of a
12619*67e74705SXin Li /// class-head (i.e. no typedefs in the scope chain), template
12620*67e74705SXin Li /// parameters are required to match up with simple template-ids, &c.
12621*67e74705SXin Li /// However, unlike when declaring a template specialization, it's
12622*67e74705SXin Li /// okay to refer to a template specialization without an empty
12623*67e74705SXin Li /// template parameter declaration, e.g.
12624*67e74705SXin Li /// friend class A<T>::B<unsigned>;
12625*67e74705SXin Li /// We permit this as a special case; if there are any template
12626*67e74705SXin Li /// parameters present at all, require proper matching, i.e.
12627*67e74705SXin Li /// template <> template \<class T> friend class A<int>::B;
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams)12628*67e74705SXin Li Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12629*67e74705SXin Li MultiTemplateParamsArg TempParams) {
12630*67e74705SXin Li SourceLocation Loc = DS.getLocStart();
12631*67e74705SXin Li
12632*67e74705SXin Li assert(DS.isFriendSpecified());
12633*67e74705SXin Li assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12634*67e74705SXin Li
12635*67e74705SXin Li // Try to convert the decl specifier to a type. This works for
12636*67e74705SXin Li // friend templates because ActOnTag never produces a ClassTemplateDecl
12637*67e74705SXin Li // for a TUK_Friend.
12638*67e74705SXin Li Declarator TheDeclarator(DS, Declarator::MemberContext);
12639*67e74705SXin Li TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12640*67e74705SXin Li QualType T = TSI->getType();
12641*67e74705SXin Li if (TheDeclarator.isInvalidType())
12642*67e74705SXin Li return nullptr;
12643*67e74705SXin Li
12644*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12645*67e74705SXin Li return nullptr;
12646*67e74705SXin Li
12647*67e74705SXin Li // This is definitely an error in C++98. It's probably meant to
12648*67e74705SXin Li // be forbidden in C++0x, too, but the specification is just
12649*67e74705SXin Li // poorly written.
12650*67e74705SXin Li //
12651*67e74705SXin Li // The problem is with declarations like the following:
12652*67e74705SXin Li // template <T> friend A<T>::foo;
12653*67e74705SXin Li // where deciding whether a class C is a friend or not now hinges
12654*67e74705SXin Li // on whether there exists an instantiation of A that causes
12655*67e74705SXin Li // 'foo' to equal C. There are restrictions on class-heads
12656*67e74705SXin Li // (which we declare (by fiat) elaborated friend declarations to
12657*67e74705SXin Li // be) that makes this tractable.
12658*67e74705SXin Li //
12659*67e74705SXin Li // FIXME: handle "template <> friend class A<T>;", which
12660*67e74705SXin Li // is possibly well-formed? Who even knows?
12661*67e74705SXin Li if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12662*67e74705SXin Li Diag(Loc, diag::err_tagless_friend_type_template)
12663*67e74705SXin Li << DS.getSourceRange();
12664*67e74705SXin Li return nullptr;
12665*67e74705SXin Li }
12666*67e74705SXin Li
12667*67e74705SXin Li // C++98 [class.friend]p1: A friend of a class is a function
12668*67e74705SXin Li // or class that is not a member of the class . . .
12669*67e74705SXin Li // This is fixed in DR77, which just barely didn't make the C++03
12670*67e74705SXin Li // deadline. It's also a very silly restriction that seriously
12671*67e74705SXin Li // affects inner classes and which nobody else seems to implement;
12672*67e74705SXin Li // thus we never diagnose it, not even in -pedantic.
12673*67e74705SXin Li //
12674*67e74705SXin Li // But note that we could warn about it: it's always useless to
12675*67e74705SXin Li // friend one of your own members (it's not, however, worthless to
12676*67e74705SXin Li // friend a member of an arbitrary specialization of your template).
12677*67e74705SXin Li
12678*67e74705SXin Li Decl *D;
12679*67e74705SXin Li if (!TempParams.empty())
12680*67e74705SXin Li D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12681*67e74705SXin Li TempParams,
12682*67e74705SXin Li TSI,
12683*67e74705SXin Li DS.getFriendSpecLoc());
12684*67e74705SXin Li else
12685*67e74705SXin Li D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12686*67e74705SXin Li
12687*67e74705SXin Li if (!D)
12688*67e74705SXin Li return nullptr;
12689*67e74705SXin Li
12690*67e74705SXin Li D->setAccess(AS_public);
12691*67e74705SXin Li CurContext->addDecl(D);
12692*67e74705SXin Li
12693*67e74705SXin Li return D;
12694*67e74705SXin Li }
12695*67e74705SXin Li
ActOnFriendFunctionDecl(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParams)12696*67e74705SXin Li NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12697*67e74705SXin Li MultiTemplateParamsArg TemplateParams) {
12698*67e74705SXin Li const DeclSpec &DS = D.getDeclSpec();
12699*67e74705SXin Li
12700*67e74705SXin Li assert(DS.isFriendSpecified());
12701*67e74705SXin Li assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12702*67e74705SXin Li
12703*67e74705SXin Li SourceLocation Loc = D.getIdentifierLoc();
12704*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12705*67e74705SXin Li
12706*67e74705SXin Li // C++ [class.friend]p1
12707*67e74705SXin Li // A friend of a class is a function or class....
12708*67e74705SXin Li // Note that this sees through typedefs, which is intended.
12709*67e74705SXin Li // It *doesn't* see through dependent types, which is correct
12710*67e74705SXin Li // according to [temp.arg.type]p3:
12711*67e74705SXin Li // If a declaration acquires a function type through a
12712*67e74705SXin Li // type dependent on a template-parameter and this causes
12713*67e74705SXin Li // a declaration that does not use the syntactic form of a
12714*67e74705SXin Li // function declarator to have a function type, the program
12715*67e74705SXin Li // is ill-formed.
12716*67e74705SXin Li if (!TInfo->getType()->isFunctionType()) {
12717*67e74705SXin Li Diag(Loc, diag::err_unexpected_friend);
12718*67e74705SXin Li
12719*67e74705SXin Li // It might be worthwhile to try to recover by creating an
12720*67e74705SXin Li // appropriate declaration.
12721*67e74705SXin Li return nullptr;
12722*67e74705SXin Li }
12723*67e74705SXin Li
12724*67e74705SXin Li // C++ [namespace.memdef]p3
12725*67e74705SXin Li // - If a friend declaration in a non-local class first declares a
12726*67e74705SXin Li // class or function, the friend class or function is a member
12727*67e74705SXin Li // of the innermost enclosing namespace.
12728*67e74705SXin Li // - The name of the friend is not found by simple name lookup
12729*67e74705SXin Li // until a matching declaration is provided in that namespace
12730*67e74705SXin Li // scope (either before or after the class declaration granting
12731*67e74705SXin Li // friendship).
12732*67e74705SXin Li // - If a friend function is called, its name may be found by the
12733*67e74705SXin Li // name lookup that considers functions from namespaces and
12734*67e74705SXin Li // classes associated with the types of the function arguments.
12735*67e74705SXin Li // - When looking for a prior declaration of a class or a function
12736*67e74705SXin Li // declared as a friend, scopes outside the innermost enclosing
12737*67e74705SXin Li // namespace scope are not considered.
12738*67e74705SXin Li
12739*67e74705SXin Li CXXScopeSpec &SS = D.getCXXScopeSpec();
12740*67e74705SXin Li DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12741*67e74705SXin Li DeclarationName Name = NameInfo.getName();
12742*67e74705SXin Li assert(Name);
12743*67e74705SXin Li
12744*67e74705SXin Li // Check for unexpanded parameter packs.
12745*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12746*67e74705SXin Li DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12747*67e74705SXin Li DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12748*67e74705SXin Li return nullptr;
12749*67e74705SXin Li
12750*67e74705SXin Li // The context we found the declaration in, or in which we should
12751*67e74705SXin Li // create the declaration.
12752*67e74705SXin Li DeclContext *DC;
12753*67e74705SXin Li Scope *DCScope = S;
12754*67e74705SXin Li LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12755*67e74705SXin Li ForRedeclaration);
12756*67e74705SXin Li
12757*67e74705SXin Li // There are five cases here.
12758*67e74705SXin Li // - There's no scope specifier and we're in a local class. Only look
12759*67e74705SXin Li // for functions declared in the immediately-enclosing block scope.
12760*67e74705SXin Li // We recover from invalid scope qualifiers as if they just weren't there.
12761*67e74705SXin Li FunctionDecl *FunctionContainingLocalClass = nullptr;
12762*67e74705SXin Li if ((SS.isInvalid() || !SS.isSet()) &&
12763*67e74705SXin Li (FunctionContainingLocalClass =
12764*67e74705SXin Li cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12765*67e74705SXin Li // C++11 [class.friend]p11:
12766*67e74705SXin Li // If a friend declaration appears in a local class and the name
12767*67e74705SXin Li // specified is an unqualified name, a prior declaration is
12768*67e74705SXin Li // looked up without considering scopes that are outside the
12769*67e74705SXin Li // innermost enclosing non-class scope. For a friend function
12770*67e74705SXin Li // declaration, if there is no prior declaration, the program is
12771*67e74705SXin Li // ill-formed.
12772*67e74705SXin Li
12773*67e74705SXin Li // Find the innermost enclosing non-class scope. This is the block
12774*67e74705SXin Li // scope containing the local class definition (or for a nested class,
12775*67e74705SXin Li // the outer local class).
12776*67e74705SXin Li DCScope = S->getFnParent();
12777*67e74705SXin Li
12778*67e74705SXin Li // Look up the function name in the scope.
12779*67e74705SXin Li Previous.clear(LookupLocalFriendName);
12780*67e74705SXin Li LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12781*67e74705SXin Li
12782*67e74705SXin Li if (!Previous.empty()) {
12783*67e74705SXin Li // All possible previous declarations must have the same context:
12784*67e74705SXin Li // either they were declared at block scope or they are members of
12785*67e74705SXin Li // one of the enclosing local classes.
12786*67e74705SXin Li DC = Previous.getRepresentativeDecl()->getDeclContext();
12787*67e74705SXin Li } else {
12788*67e74705SXin Li // This is ill-formed, but provide the context that we would have
12789*67e74705SXin Li // declared the function in, if we were permitted to, for error recovery.
12790*67e74705SXin Li DC = FunctionContainingLocalClass;
12791*67e74705SXin Li }
12792*67e74705SXin Li adjustContextForLocalExternDecl(DC);
12793*67e74705SXin Li
12794*67e74705SXin Li // C++ [class.friend]p6:
12795*67e74705SXin Li // A function can be defined in a friend declaration of a class if and
12796*67e74705SXin Li // only if the class is a non-local class (9.8), the function name is
12797*67e74705SXin Li // unqualified, and the function has namespace scope.
12798*67e74705SXin Li if (D.isFunctionDefinition()) {
12799*67e74705SXin Li Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12800*67e74705SXin Li }
12801*67e74705SXin Li
12802*67e74705SXin Li // - There's no scope specifier, in which case we just go to the
12803*67e74705SXin Li // appropriate scope and look for a function or function template
12804*67e74705SXin Li // there as appropriate.
12805*67e74705SXin Li } else if (SS.isInvalid() || !SS.isSet()) {
12806*67e74705SXin Li // C++11 [namespace.memdef]p3:
12807*67e74705SXin Li // If the name in a friend declaration is neither qualified nor
12808*67e74705SXin Li // a template-id and the declaration is a function or an
12809*67e74705SXin Li // elaborated-type-specifier, the lookup to determine whether
12810*67e74705SXin Li // the entity has been previously declared shall not consider
12811*67e74705SXin Li // any scopes outside the innermost enclosing namespace.
12812*67e74705SXin Li bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12813*67e74705SXin Li
12814*67e74705SXin Li // Find the appropriate context according to the above.
12815*67e74705SXin Li DC = CurContext;
12816*67e74705SXin Li
12817*67e74705SXin Li // Skip class contexts. If someone can cite chapter and verse
12818*67e74705SXin Li // for this behavior, that would be nice --- it's what GCC and
12819*67e74705SXin Li // EDG do, and it seems like a reasonable intent, but the spec
12820*67e74705SXin Li // really only says that checks for unqualified existing
12821*67e74705SXin Li // declarations should stop at the nearest enclosing namespace,
12822*67e74705SXin Li // not that they should only consider the nearest enclosing
12823*67e74705SXin Li // namespace.
12824*67e74705SXin Li while (DC->isRecord())
12825*67e74705SXin Li DC = DC->getParent();
12826*67e74705SXin Li
12827*67e74705SXin Li DeclContext *LookupDC = DC;
12828*67e74705SXin Li while (LookupDC->isTransparentContext())
12829*67e74705SXin Li LookupDC = LookupDC->getParent();
12830*67e74705SXin Li
12831*67e74705SXin Li while (true) {
12832*67e74705SXin Li LookupQualifiedName(Previous, LookupDC);
12833*67e74705SXin Li
12834*67e74705SXin Li if (!Previous.empty()) {
12835*67e74705SXin Li DC = LookupDC;
12836*67e74705SXin Li break;
12837*67e74705SXin Li }
12838*67e74705SXin Li
12839*67e74705SXin Li if (isTemplateId) {
12840*67e74705SXin Li if (isa<TranslationUnitDecl>(LookupDC)) break;
12841*67e74705SXin Li } else {
12842*67e74705SXin Li if (LookupDC->isFileContext()) break;
12843*67e74705SXin Li }
12844*67e74705SXin Li LookupDC = LookupDC->getParent();
12845*67e74705SXin Li }
12846*67e74705SXin Li
12847*67e74705SXin Li DCScope = getScopeForDeclContext(S, DC);
12848*67e74705SXin Li
12849*67e74705SXin Li // - There's a non-dependent scope specifier, in which case we
12850*67e74705SXin Li // compute it and do a previous lookup there for a function
12851*67e74705SXin Li // or function template.
12852*67e74705SXin Li } else if (!SS.getScopeRep()->isDependent()) {
12853*67e74705SXin Li DC = computeDeclContext(SS);
12854*67e74705SXin Li if (!DC) return nullptr;
12855*67e74705SXin Li
12856*67e74705SXin Li if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12857*67e74705SXin Li
12858*67e74705SXin Li LookupQualifiedName(Previous, DC);
12859*67e74705SXin Li
12860*67e74705SXin Li // Ignore things found implicitly in the wrong scope.
12861*67e74705SXin Li // TODO: better diagnostics for this case. Suggesting the right
12862*67e74705SXin Li // qualified scope would be nice...
12863*67e74705SXin Li LookupResult::Filter F = Previous.makeFilter();
12864*67e74705SXin Li while (F.hasNext()) {
12865*67e74705SXin Li NamedDecl *D = F.next();
12866*67e74705SXin Li if (!DC->InEnclosingNamespaceSetOf(
12867*67e74705SXin Li D->getDeclContext()->getRedeclContext()))
12868*67e74705SXin Li F.erase();
12869*67e74705SXin Li }
12870*67e74705SXin Li F.done();
12871*67e74705SXin Li
12872*67e74705SXin Li if (Previous.empty()) {
12873*67e74705SXin Li D.setInvalidType();
12874*67e74705SXin Li Diag(Loc, diag::err_qualified_friend_not_found)
12875*67e74705SXin Li << Name << TInfo->getType();
12876*67e74705SXin Li return nullptr;
12877*67e74705SXin Li }
12878*67e74705SXin Li
12879*67e74705SXin Li // C++ [class.friend]p1: A friend of a class is a function or
12880*67e74705SXin Li // class that is not a member of the class . . .
12881*67e74705SXin Li if (DC->Equals(CurContext))
12882*67e74705SXin Li Diag(DS.getFriendSpecLoc(),
12883*67e74705SXin Li getLangOpts().CPlusPlus11 ?
12884*67e74705SXin Li diag::warn_cxx98_compat_friend_is_member :
12885*67e74705SXin Li diag::err_friend_is_member);
12886*67e74705SXin Li
12887*67e74705SXin Li if (D.isFunctionDefinition()) {
12888*67e74705SXin Li // C++ [class.friend]p6:
12889*67e74705SXin Li // A function can be defined in a friend declaration of a class if and
12890*67e74705SXin Li // only if the class is a non-local class (9.8), the function name is
12891*67e74705SXin Li // unqualified, and the function has namespace scope.
12892*67e74705SXin Li SemaDiagnosticBuilder DB
12893*67e74705SXin Li = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12894*67e74705SXin Li
12895*67e74705SXin Li DB << SS.getScopeRep();
12896*67e74705SXin Li if (DC->isFileContext())
12897*67e74705SXin Li DB << FixItHint::CreateRemoval(SS.getRange());
12898*67e74705SXin Li SS.clear();
12899*67e74705SXin Li }
12900*67e74705SXin Li
12901*67e74705SXin Li // - There's a scope specifier that does not match any template
12902*67e74705SXin Li // parameter lists, in which case we use some arbitrary context,
12903*67e74705SXin Li // create a method or method template, and wait for instantiation.
12904*67e74705SXin Li // - There's a scope specifier that does match some template
12905*67e74705SXin Li // parameter lists, which we don't handle right now.
12906*67e74705SXin Li } else {
12907*67e74705SXin Li if (D.isFunctionDefinition()) {
12908*67e74705SXin Li // C++ [class.friend]p6:
12909*67e74705SXin Li // A function can be defined in a friend declaration of a class if and
12910*67e74705SXin Li // only if the class is a non-local class (9.8), the function name is
12911*67e74705SXin Li // unqualified, and the function has namespace scope.
12912*67e74705SXin Li Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12913*67e74705SXin Li << SS.getScopeRep();
12914*67e74705SXin Li }
12915*67e74705SXin Li
12916*67e74705SXin Li DC = CurContext;
12917*67e74705SXin Li assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12918*67e74705SXin Li }
12919*67e74705SXin Li
12920*67e74705SXin Li if (!DC->isRecord()) {
12921*67e74705SXin Li int DiagArg = -1;
12922*67e74705SXin Li switch (D.getName().getKind()) {
12923*67e74705SXin Li case UnqualifiedId::IK_ConstructorTemplateId:
12924*67e74705SXin Li case UnqualifiedId::IK_ConstructorName:
12925*67e74705SXin Li DiagArg = 0;
12926*67e74705SXin Li break;
12927*67e74705SXin Li case UnqualifiedId::IK_DestructorName:
12928*67e74705SXin Li DiagArg = 1;
12929*67e74705SXin Li break;
12930*67e74705SXin Li case UnqualifiedId::IK_ConversionFunctionId:
12931*67e74705SXin Li DiagArg = 2;
12932*67e74705SXin Li break;
12933*67e74705SXin Li case UnqualifiedId::IK_Identifier:
12934*67e74705SXin Li case UnqualifiedId::IK_ImplicitSelfParam:
12935*67e74705SXin Li case UnqualifiedId::IK_LiteralOperatorId:
12936*67e74705SXin Li case UnqualifiedId::IK_OperatorFunctionId:
12937*67e74705SXin Li case UnqualifiedId::IK_TemplateId:
12938*67e74705SXin Li break;
12939*67e74705SXin Li }
12940*67e74705SXin Li // This implies that it has to be an operator or function.
12941*67e74705SXin Li if (DiagArg >= 0) {
12942*67e74705SXin Li Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
12943*67e74705SXin Li return nullptr;
12944*67e74705SXin Li }
12945*67e74705SXin Li }
12946*67e74705SXin Li
12947*67e74705SXin Li // FIXME: This is an egregious hack to cope with cases where the scope stack
12948*67e74705SXin Li // does not contain the declaration context, i.e., in an out-of-line
12949*67e74705SXin Li // definition of a class.
12950*67e74705SXin Li Scope FakeDCScope(S, Scope::DeclScope, Diags);
12951*67e74705SXin Li if (!DCScope) {
12952*67e74705SXin Li FakeDCScope.setEntity(DC);
12953*67e74705SXin Li DCScope = &FakeDCScope;
12954*67e74705SXin Li }
12955*67e74705SXin Li
12956*67e74705SXin Li bool AddToScope = true;
12957*67e74705SXin Li NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12958*67e74705SXin Li TemplateParams, AddToScope);
12959*67e74705SXin Li if (!ND) return nullptr;
12960*67e74705SXin Li
12961*67e74705SXin Li assert(ND->getLexicalDeclContext() == CurContext);
12962*67e74705SXin Li
12963*67e74705SXin Li // If we performed typo correction, we might have added a scope specifier
12964*67e74705SXin Li // and changed the decl context.
12965*67e74705SXin Li DC = ND->getDeclContext();
12966*67e74705SXin Li
12967*67e74705SXin Li // Add the function declaration to the appropriate lookup tables,
12968*67e74705SXin Li // adjusting the redeclarations list as necessary. We don't
12969*67e74705SXin Li // want to do this yet if the friending class is dependent.
12970*67e74705SXin Li //
12971*67e74705SXin Li // Also update the scope-based lookup if the target context's
12972*67e74705SXin Li // lookup context is in lexical scope.
12973*67e74705SXin Li if (!CurContext->isDependentContext()) {
12974*67e74705SXin Li DC = DC->getRedeclContext();
12975*67e74705SXin Li DC->makeDeclVisibleInContext(ND);
12976*67e74705SXin Li if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12977*67e74705SXin Li PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12978*67e74705SXin Li }
12979*67e74705SXin Li
12980*67e74705SXin Li FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12981*67e74705SXin Li D.getIdentifierLoc(), ND,
12982*67e74705SXin Li DS.getFriendSpecLoc());
12983*67e74705SXin Li FrD->setAccess(AS_public);
12984*67e74705SXin Li CurContext->addDecl(FrD);
12985*67e74705SXin Li
12986*67e74705SXin Li if (ND->isInvalidDecl()) {
12987*67e74705SXin Li FrD->setInvalidDecl();
12988*67e74705SXin Li } else {
12989*67e74705SXin Li if (DC->isRecord()) CheckFriendAccess(ND);
12990*67e74705SXin Li
12991*67e74705SXin Li FunctionDecl *FD;
12992*67e74705SXin Li if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12993*67e74705SXin Li FD = FTD->getTemplatedDecl();
12994*67e74705SXin Li else
12995*67e74705SXin Li FD = cast<FunctionDecl>(ND);
12996*67e74705SXin Li
12997*67e74705SXin Li // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12998*67e74705SXin Li // default argument expression, that declaration shall be a definition
12999*67e74705SXin Li // and shall be the only declaration of the function or function
13000*67e74705SXin Li // template in the translation unit.
13001*67e74705SXin Li if (functionDeclHasDefaultArgument(FD)) {
13002*67e74705SXin Li if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
13003*67e74705SXin Li Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13004*67e74705SXin Li Diag(OldFD->getLocation(), diag::note_previous_declaration);
13005*67e74705SXin Li } else if (!D.isFunctionDefinition())
13006*67e74705SXin Li Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13007*67e74705SXin Li }
13008*67e74705SXin Li
13009*67e74705SXin Li // Mark templated-scope function declarations as unsupported.
13010*67e74705SXin Li if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13011*67e74705SXin Li Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13012*67e74705SXin Li << SS.getScopeRep() << SS.getRange()
13013*67e74705SXin Li << cast<CXXRecordDecl>(CurContext);
13014*67e74705SXin Li FrD->setUnsupportedFriend(true);
13015*67e74705SXin Li }
13016*67e74705SXin Li }
13017*67e74705SXin Li
13018*67e74705SXin Li return ND;
13019*67e74705SXin Li }
13020*67e74705SXin Li
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc)13021*67e74705SXin Li void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13022*67e74705SXin Li AdjustDeclIfTemplate(Dcl);
13023*67e74705SXin Li
13024*67e74705SXin Li FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13025*67e74705SXin Li if (!Fn) {
13026*67e74705SXin Li Diag(DelLoc, diag::err_deleted_non_function);
13027*67e74705SXin Li return;
13028*67e74705SXin Li }
13029*67e74705SXin Li
13030*67e74705SXin Li if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13031*67e74705SXin Li // Don't consider the implicit declaration we generate for explicit
13032*67e74705SXin Li // specializations. FIXME: Do not generate these implicit declarations.
13033*67e74705SXin Li if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13034*67e74705SXin Li Prev->getPreviousDecl()) &&
13035*67e74705SXin Li !Prev->isDefined()) {
13036*67e74705SXin Li Diag(DelLoc, diag::err_deleted_decl_not_first);
13037*67e74705SXin Li Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13038*67e74705SXin Li Prev->isImplicit() ? diag::note_previous_implicit_declaration
13039*67e74705SXin Li : diag::note_previous_declaration);
13040*67e74705SXin Li }
13041*67e74705SXin Li // If the declaration wasn't the first, we delete the function anyway for
13042*67e74705SXin Li // recovery.
13043*67e74705SXin Li Fn = Fn->getCanonicalDecl();
13044*67e74705SXin Li }
13045*67e74705SXin Li
13046*67e74705SXin Li // dllimport/dllexport cannot be deleted.
13047*67e74705SXin Li if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13048*67e74705SXin Li Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13049*67e74705SXin Li Fn->setInvalidDecl();
13050*67e74705SXin Li }
13051*67e74705SXin Li
13052*67e74705SXin Li if (Fn->isDeleted())
13053*67e74705SXin Li return;
13054*67e74705SXin Li
13055*67e74705SXin Li // See if we're deleting a function which is already known to override a
13056*67e74705SXin Li // non-deleted virtual function.
13057*67e74705SXin Li if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13058*67e74705SXin Li bool IssuedDiagnostic = false;
13059*67e74705SXin Li for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13060*67e74705SXin Li E = MD->end_overridden_methods();
13061*67e74705SXin Li I != E; ++I) {
13062*67e74705SXin Li if (!(*MD->begin_overridden_methods())->isDeleted()) {
13063*67e74705SXin Li if (!IssuedDiagnostic) {
13064*67e74705SXin Li Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13065*67e74705SXin Li IssuedDiagnostic = true;
13066*67e74705SXin Li }
13067*67e74705SXin Li Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13068*67e74705SXin Li }
13069*67e74705SXin Li }
13070*67e74705SXin Li }
13071*67e74705SXin Li
13072*67e74705SXin Li // C++11 [basic.start.main]p3:
13073*67e74705SXin Li // A program that defines main as deleted [...] is ill-formed.
13074*67e74705SXin Li if (Fn->isMain())
13075*67e74705SXin Li Diag(DelLoc, diag::err_deleted_main);
13076*67e74705SXin Li
13077*67e74705SXin Li Fn->setDeletedAsWritten();
13078*67e74705SXin Li }
13079*67e74705SXin Li
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)13080*67e74705SXin Li void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13081*67e74705SXin Li CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13082*67e74705SXin Li
13083*67e74705SXin Li if (MD) {
13084*67e74705SXin Li if (MD->getParent()->isDependentType()) {
13085*67e74705SXin Li MD->setDefaulted();
13086*67e74705SXin Li MD->setExplicitlyDefaulted();
13087*67e74705SXin Li return;
13088*67e74705SXin Li }
13089*67e74705SXin Li
13090*67e74705SXin Li CXXSpecialMember Member = getSpecialMember(MD);
13091*67e74705SXin Li if (Member == CXXInvalid) {
13092*67e74705SXin Li if (!MD->isInvalidDecl())
13093*67e74705SXin Li Diag(DefaultLoc, diag::err_default_special_members);
13094*67e74705SXin Li return;
13095*67e74705SXin Li }
13096*67e74705SXin Li
13097*67e74705SXin Li MD->setDefaulted();
13098*67e74705SXin Li MD->setExplicitlyDefaulted();
13099*67e74705SXin Li
13100*67e74705SXin Li // If this definition appears within the record, do the checking when
13101*67e74705SXin Li // the record is complete.
13102*67e74705SXin Li const FunctionDecl *Primary = MD;
13103*67e74705SXin Li if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13104*67e74705SXin Li // Ask the template instantiation pattern that actually had the
13105*67e74705SXin Li // '= default' on it.
13106*67e74705SXin Li Primary = Pattern;
13107*67e74705SXin Li
13108*67e74705SXin Li // If the method was defaulted on its first declaration, we will have
13109*67e74705SXin Li // already performed the checking in CheckCompletedCXXClass. Such a
13110*67e74705SXin Li // declaration doesn't trigger an implicit definition.
13111*67e74705SXin Li if (Primary->getCanonicalDecl()->isDefaulted())
13112*67e74705SXin Li return;
13113*67e74705SXin Li
13114*67e74705SXin Li CheckExplicitlyDefaultedSpecialMember(MD);
13115*67e74705SXin Li
13116*67e74705SXin Li if (!MD->isInvalidDecl())
13117*67e74705SXin Li DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13118*67e74705SXin Li } else {
13119*67e74705SXin Li Diag(DefaultLoc, diag::err_default_special_members);
13120*67e74705SXin Li }
13121*67e74705SXin Li }
13122*67e74705SXin Li
SearchForReturnInStmt(Sema & Self,Stmt * S)13123*67e74705SXin Li static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13124*67e74705SXin Li for (Stmt *SubStmt : S->children()) {
13125*67e74705SXin Li if (!SubStmt)
13126*67e74705SXin Li continue;
13127*67e74705SXin Li if (isa<ReturnStmt>(SubStmt))
13128*67e74705SXin Li Self.Diag(SubStmt->getLocStart(),
13129*67e74705SXin Li diag::err_return_in_constructor_handler);
13130*67e74705SXin Li if (!isa<Expr>(SubStmt))
13131*67e74705SXin Li SearchForReturnInStmt(Self, SubStmt);
13132*67e74705SXin Li }
13133*67e74705SXin Li }
13134*67e74705SXin Li
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)13135*67e74705SXin Li void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13136*67e74705SXin Li for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13137*67e74705SXin Li CXXCatchStmt *Handler = TryBlock->getHandler(I);
13138*67e74705SXin Li SearchForReturnInStmt(*this, Handler);
13139*67e74705SXin Li }
13140*67e74705SXin Li }
13141*67e74705SXin Li
CheckOverridingFunctionAttributes(const CXXMethodDecl * New,const CXXMethodDecl * Old)13142*67e74705SXin Li bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13143*67e74705SXin Li const CXXMethodDecl *Old) {
13144*67e74705SXin Li const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13145*67e74705SXin Li const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13146*67e74705SXin Li
13147*67e74705SXin Li CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13148*67e74705SXin Li
13149*67e74705SXin Li // If the calling conventions match, everything is fine
13150*67e74705SXin Li if (NewCC == OldCC)
13151*67e74705SXin Li return false;
13152*67e74705SXin Li
13153*67e74705SXin Li // If the calling conventions mismatch because the new function is static,
13154*67e74705SXin Li // suppress the calling convention mismatch error; the error about static
13155*67e74705SXin Li // function override (err_static_overrides_virtual from
13156*67e74705SXin Li // Sema::CheckFunctionDeclaration) is more clear.
13157*67e74705SXin Li if (New->getStorageClass() == SC_Static)
13158*67e74705SXin Li return false;
13159*67e74705SXin Li
13160*67e74705SXin Li Diag(New->getLocation(),
13161*67e74705SXin Li diag::err_conflicting_overriding_cc_attributes)
13162*67e74705SXin Li << New->getDeclName() << New->getType() << Old->getType();
13163*67e74705SXin Li Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13164*67e74705SXin Li return true;
13165*67e74705SXin Li }
13166*67e74705SXin Li
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)13167*67e74705SXin Li bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13168*67e74705SXin Li const CXXMethodDecl *Old) {
13169*67e74705SXin Li QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13170*67e74705SXin Li QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13171*67e74705SXin Li
13172*67e74705SXin Li if (Context.hasSameType(NewTy, OldTy) ||
13173*67e74705SXin Li NewTy->isDependentType() || OldTy->isDependentType())
13174*67e74705SXin Li return false;
13175*67e74705SXin Li
13176*67e74705SXin Li // Check if the return types are covariant
13177*67e74705SXin Li QualType NewClassTy, OldClassTy;
13178*67e74705SXin Li
13179*67e74705SXin Li /// Both types must be pointers or references to classes.
13180*67e74705SXin Li if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13181*67e74705SXin Li if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13182*67e74705SXin Li NewClassTy = NewPT->getPointeeType();
13183*67e74705SXin Li OldClassTy = OldPT->getPointeeType();
13184*67e74705SXin Li }
13185*67e74705SXin Li } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13186*67e74705SXin Li if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13187*67e74705SXin Li if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13188*67e74705SXin Li NewClassTy = NewRT->getPointeeType();
13189*67e74705SXin Li OldClassTy = OldRT->getPointeeType();
13190*67e74705SXin Li }
13191*67e74705SXin Li }
13192*67e74705SXin Li }
13193*67e74705SXin Li
13194*67e74705SXin Li // The return types aren't either both pointers or references to a class type.
13195*67e74705SXin Li if (NewClassTy.isNull()) {
13196*67e74705SXin Li Diag(New->getLocation(),
13197*67e74705SXin Li diag::err_different_return_type_for_overriding_virtual_function)
13198*67e74705SXin Li << New->getDeclName() << NewTy << OldTy
13199*67e74705SXin Li << New->getReturnTypeSourceRange();
13200*67e74705SXin Li Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13201*67e74705SXin Li << Old->getReturnTypeSourceRange();
13202*67e74705SXin Li
13203*67e74705SXin Li return true;
13204*67e74705SXin Li }
13205*67e74705SXin Li
13206*67e74705SXin Li if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13207*67e74705SXin Li // C++14 [class.virtual]p8:
13208*67e74705SXin Li // If the class type in the covariant return type of D::f differs from
13209*67e74705SXin Li // that of B::f, the class type in the return type of D::f shall be
13210*67e74705SXin Li // complete at the point of declaration of D::f or shall be the class
13211*67e74705SXin Li // type D.
13212*67e74705SXin Li if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13213*67e74705SXin Li if (!RT->isBeingDefined() &&
13214*67e74705SXin Li RequireCompleteType(New->getLocation(), NewClassTy,
13215*67e74705SXin Li diag::err_covariant_return_incomplete,
13216*67e74705SXin Li New->getDeclName()))
13217*67e74705SXin Li return true;
13218*67e74705SXin Li }
13219*67e74705SXin Li
13220*67e74705SXin Li // Check if the new class derives from the old class.
13221*67e74705SXin Li if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13222*67e74705SXin Li Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13223*67e74705SXin Li << New->getDeclName() << NewTy << OldTy
13224*67e74705SXin Li << New->getReturnTypeSourceRange();
13225*67e74705SXin Li Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13226*67e74705SXin Li << Old->getReturnTypeSourceRange();
13227*67e74705SXin Li return true;
13228*67e74705SXin Li }
13229*67e74705SXin Li
13230*67e74705SXin Li // Check if we the conversion from derived to base is valid.
13231*67e74705SXin Li if (CheckDerivedToBaseConversion(
13232*67e74705SXin Li NewClassTy, OldClassTy,
13233*67e74705SXin Li diag::err_covariant_return_inaccessible_base,
13234*67e74705SXin Li diag::err_covariant_return_ambiguous_derived_to_base_conv,
13235*67e74705SXin Li New->getLocation(), New->getReturnTypeSourceRange(),
13236*67e74705SXin Li New->getDeclName(), nullptr)) {
13237*67e74705SXin Li // FIXME: this note won't trigger for delayed access control
13238*67e74705SXin Li // diagnostics, and it's impossible to get an undelayed error
13239*67e74705SXin Li // here from access control during the original parse because
13240*67e74705SXin Li // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13241*67e74705SXin Li Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13242*67e74705SXin Li << Old->getReturnTypeSourceRange();
13243*67e74705SXin Li return true;
13244*67e74705SXin Li }
13245*67e74705SXin Li }
13246*67e74705SXin Li
13247*67e74705SXin Li // The qualifiers of the return types must be the same.
13248*67e74705SXin Li if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13249*67e74705SXin Li Diag(New->getLocation(),
13250*67e74705SXin Li diag::err_covariant_return_type_different_qualifications)
13251*67e74705SXin Li << New->getDeclName() << NewTy << OldTy
13252*67e74705SXin Li << New->getReturnTypeSourceRange();
13253*67e74705SXin Li Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13254*67e74705SXin Li << Old->getReturnTypeSourceRange();
13255*67e74705SXin Li return true;
13256*67e74705SXin Li }
13257*67e74705SXin Li
13258*67e74705SXin Li
13259*67e74705SXin Li // The new class type must have the same or less qualifiers as the old type.
13260*67e74705SXin Li if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13261*67e74705SXin Li Diag(New->getLocation(),
13262*67e74705SXin Li diag::err_covariant_return_type_class_type_more_qualified)
13263*67e74705SXin Li << New->getDeclName() << NewTy << OldTy
13264*67e74705SXin Li << New->getReturnTypeSourceRange();
13265*67e74705SXin Li Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13266*67e74705SXin Li << Old->getReturnTypeSourceRange();
13267*67e74705SXin Li return true;
13268*67e74705SXin Li }
13269*67e74705SXin Li
13270*67e74705SXin Li return false;
13271*67e74705SXin Li }
13272*67e74705SXin Li
13273*67e74705SXin Li /// \brief Mark the given method pure.
13274*67e74705SXin Li ///
13275*67e74705SXin Li /// \param Method the method to be marked pure.
13276*67e74705SXin Li ///
13277*67e74705SXin Li /// \param InitRange the source range that covers the "0" initializer.
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)13278*67e74705SXin Li bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13279*67e74705SXin Li SourceLocation EndLoc = InitRange.getEnd();
13280*67e74705SXin Li if (EndLoc.isValid())
13281*67e74705SXin Li Method->setRangeEnd(EndLoc);
13282*67e74705SXin Li
13283*67e74705SXin Li if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13284*67e74705SXin Li Method->setPure();
13285*67e74705SXin Li return false;
13286*67e74705SXin Li }
13287*67e74705SXin Li
13288*67e74705SXin Li if (!Method->isInvalidDecl())
13289*67e74705SXin Li Diag(Method->getLocation(), diag::err_non_virtual_pure)
13290*67e74705SXin Li << Method->getDeclName() << InitRange;
13291*67e74705SXin Li return true;
13292*67e74705SXin Li }
13293*67e74705SXin Li
ActOnPureSpecifier(Decl * D,SourceLocation ZeroLoc)13294*67e74705SXin Li void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13295*67e74705SXin Li if (D->getFriendObjectKind())
13296*67e74705SXin Li Diag(D->getLocation(), diag::err_pure_friend);
13297*67e74705SXin Li else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13298*67e74705SXin Li CheckPureMethod(M, ZeroLoc);
13299*67e74705SXin Li else
13300*67e74705SXin Li Diag(D->getLocation(), diag::err_illegal_initializer);
13301*67e74705SXin Li }
13302*67e74705SXin Li
13303*67e74705SXin Li /// \brief Determine whether the given declaration is a static data member.
isStaticDataMember(const Decl * D)13304*67e74705SXin Li static bool isStaticDataMember(const Decl *D) {
13305*67e74705SXin Li if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13306*67e74705SXin Li return Var->isStaticDataMember();
13307*67e74705SXin Li
13308*67e74705SXin Li return false;
13309*67e74705SXin Li }
13310*67e74705SXin Li
13311*67e74705SXin Li /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13312*67e74705SXin Li /// an initializer for the out-of-line declaration 'Dcl'. The scope
13313*67e74705SXin Li /// is a fresh scope pushed for just this purpose.
13314*67e74705SXin Li ///
13315*67e74705SXin Li /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13316*67e74705SXin Li /// static data member of class X, names should be looked up in the scope of
13317*67e74705SXin Li /// class X.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)13318*67e74705SXin Li void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13319*67e74705SXin Li // If there is no declaration, there was an error parsing it.
13320*67e74705SXin Li if (!D || D->isInvalidDecl())
13321*67e74705SXin Li return;
13322*67e74705SXin Li
13323*67e74705SXin Li // We will always have a nested name specifier here, but this declaration
13324*67e74705SXin Li // might not be out of line if the specifier names the current namespace:
13325*67e74705SXin Li // extern int n;
13326*67e74705SXin Li // int ::n = 0;
13327*67e74705SXin Li if (D->isOutOfLine())
13328*67e74705SXin Li EnterDeclaratorContext(S, D->getDeclContext());
13329*67e74705SXin Li
13330*67e74705SXin Li // If we are parsing the initializer for a static data member, push a
13331*67e74705SXin Li // new expression evaluation context that is associated with this static
13332*67e74705SXin Li // data member.
13333*67e74705SXin Li if (isStaticDataMember(D))
13334*67e74705SXin Li PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13335*67e74705SXin Li }
13336*67e74705SXin Li
13337*67e74705SXin Li /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13338*67e74705SXin Li /// initializer for the out-of-line declaration 'D'.
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)13339*67e74705SXin Li void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13340*67e74705SXin Li // If there is no declaration, there was an error parsing it.
13341*67e74705SXin Li if (!D || D->isInvalidDecl())
13342*67e74705SXin Li return;
13343*67e74705SXin Li
13344*67e74705SXin Li if (isStaticDataMember(D))
13345*67e74705SXin Li PopExpressionEvaluationContext();
13346*67e74705SXin Li
13347*67e74705SXin Li if (D->isOutOfLine())
13348*67e74705SXin Li ExitDeclaratorContext(S);
13349*67e74705SXin Li }
13350*67e74705SXin Li
13351*67e74705SXin Li /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13352*67e74705SXin Li /// C++ if/switch/while/for statement.
13353*67e74705SXin Li /// e.g: "if (int x = f()) {...}"
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)13354*67e74705SXin Li DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13355*67e74705SXin Li // C++ 6.4p2:
13356*67e74705SXin Li // The declarator shall not specify a function or an array.
13357*67e74705SXin Li // The type-specifier-seq shall not contain typedef and shall not declare a
13358*67e74705SXin Li // new class or enumeration.
13359*67e74705SXin Li assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13360*67e74705SXin Li "Parser allowed 'typedef' as storage class of condition decl.");
13361*67e74705SXin Li
13362*67e74705SXin Li Decl *Dcl = ActOnDeclarator(S, D);
13363*67e74705SXin Li if (!Dcl)
13364*67e74705SXin Li return true;
13365*67e74705SXin Li
13366*67e74705SXin Li if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13367*67e74705SXin Li Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13368*67e74705SXin Li << D.getSourceRange();
13369*67e74705SXin Li return true;
13370*67e74705SXin Li }
13371*67e74705SXin Li
13372*67e74705SXin Li return Dcl;
13373*67e74705SXin Li }
13374*67e74705SXin Li
LoadExternalVTableUses()13375*67e74705SXin Li void Sema::LoadExternalVTableUses() {
13376*67e74705SXin Li if (!ExternalSource)
13377*67e74705SXin Li return;
13378*67e74705SXin Li
13379*67e74705SXin Li SmallVector<ExternalVTableUse, 4> VTables;
13380*67e74705SXin Li ExternalSource->ReadUsedVTables(VTables);
13381*67e74705SXin Li SmallVector<VTableUse, 4> NewUses;
13382*67e74705SXin Li for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13383*67e74705SXin Li llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13384*67e74705SXin Li = VTablesUsed.find(VTables[I].Record);
13385*67e74705SXin Li // Even if a definition wasn't required before, it may be required now.
13386*67e74705SXin Li if (Pos != VTablesUsed.end()) {
13387*67e74705SXin Li if (!Pos->second && VTables[I].DefinitionRequired)
13388*67e74705SXin Li Pos->second = true;
13389*67e74705SXin Li continue;
13390*67e74705SXin Li }
13391*67e74705SXin Li
13392*67e74705SXin Li VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13393*67e74705SXin Li NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13394*67e74705SXin Li }
13395*67e74705SXin Li
13396*67e74705SXin Li VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13397*67e74705SXin Li }
13398*67e74705SXin Li
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)13399*67e74705SXin Li void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13400*67e74705SXin Li bool DefinitionRequired) {
13401*67e74705SXin Li // Ignore any vtable uses in unevaluated operands or for classes that do
13402*67e74705SXin Li // not have a vtable.
13403*67e74705SXin Li if (!Class->isDynamicClass() || Class->isDependentContext() ||
13404*67e74705SXin Li CurContext->isDependentContext() || isUnevaluatedContext())
13405*67e74705SXin Li return;
13406*67e74705SXin Li
13407*67e74705SXin Li // Try to insert this class into the map.
13408*67e74705SXin Li LoadExternalVTableUses();
13409*67e74705SXin Li Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13410*67e74705SXin Li std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13411*67e74705SXin Li Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13412*67e74705SXin Li if (!Pos.second) {
13413*67e74705SXin Li // If we already had an entry, check to see if we are promoting this vtable
13414*67e74705SXin Li // to require a definition. If so, we need to reappend to the VTableUses
13415*67e74705SXin Li // list, since we may have already processed the first entry.
13416*67e74705SXin Li if (DefinitionRequired && !Pos.first->second) {
13417*67e74705SXin Li Pos.first->second = true;
13418*67e74705SXin Li } else {
13419*67e74705SXin Li // Otherwise, we can early exit.
13420*67e74705SXin Li return;
13421*67e74705SXin Li }
13422*67e74705SXin Li } else {
13423*67e74705SXin Li // The Microsoft ABI requires that we perform the destructor body
13424*67e74705SXin Li // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13425*67e74705SXin Li // the deleting destructor is emitted with the vtable, not with the
13426*67e74705SXin Li // destructor definition as in the Itanium ABI.
13427*67e74705SXin Li if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13428*67e74705SXin Li CXXDestructorDecl *DD = Class->getDestructor();
13429*67e74705SXin Li if (DD && DD->isVirtual() && !DD->isDeleted()) {
13430*67e74705SXin Li if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
13431*67e74705SXin Li // If this is an out-of-line declaration, marking it referenced will
13432*67e74705SXin Li // not do anything. Manually call CheckDestructor to look up operator
13433*67e74705SXin Li // delete().
13434*67e74705SXin Li ContextRAII SavedContext(*this, DD);
13435*67e74705SXin Li CheckDestructor(DD);
13436*67e74705SXin Li } else {
13437*67e74705SXin Li MarkFunctionReferenced(Loc, Class->getDestructor());
13438*67e74705SXin Li }
13439*67e74705SXin Li }
13440*67e74705SXin Li }
13441*67e74705SXin Li }
13442*67e74705SXin Li
13443*67e74705SXin Li // Local classes need to have their virtual members marked
13444*67e74705SXin Li // immediately. For all other classes, we mark their virtual members
13445*67e74705SXin Li // at the end of the translation unit.
13446*67e74705SXin Li if (Class->isLocalClass())
13447*67e74705SXin Li MarkVirtualMembersReferenced(Loc, Class);
13448*67e74705SXin Li else
13449*67e74705SXin Li VTableUses.push_back(std::make_pair(Class, Loc));
13450*67e74705SXin Li }
13451*67e74705SXin Li
DefineUsedVTables()13452*67e74705SXin Li bool Sema::DefineUsedVTables() {
13453*67e74705SXin Li LoadExternalVTableUses();
13454*67e74705SXin Li if (VTableUses.empty())
13455*67e74705SXin Li return false;
13456*67e74705SXin Li
13457*67e74705SXin Li // Note: The VTableUses vector could grow as a result of marking
13458*67e74705SXin Li // the members of a class as "used", so we check the size each
13459*67e74705SXin Li // time through the loop and prefer indices (which are stable) to
13460*67e74705SXin Li // iterators (which are not).
13461*67e74705SXin Li bool DefinedAnything = false;
13462*67e74705SXin Li for (unsigned I = 0; I != VTableUses.size(); ++I) {
13463*67e74705SXin Li CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13464*67e74705SXin Li if (!Class)
13465*67e74705SXin Li continue;
13466*67e74705SXin Li
13467*67e74705SXin Li SourceLocation Loc = VTableUses[I].second;
13468*67e74705SXin Li
13469*67e74705SXin Li bool DefineVTable = true;
13470*67e74705SXin Li
13471*67e74705SXin Li // If this class has a key function, but that key function is
13472*67e74705SXin Li // defined in another translation unit, we don't need to emit the
13473*67e74705SXin Li // vtable even though we're using it.
13474*67e74705SXin Li const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13475*67e74705SXin Li if (KeyFunction && !KeyFunction->hasBody()) {
13476*67e74705SXin Li // The key function is in another translation unit.
13477*67e74705SXin Li DefineVTable = false;
13478*67e74705SXin Li TemplateSpecializationKind TSK =
13479*67e74705SXin Li KeyFunction->getTemplateSpecializationKind();
13480*67e74705SXin Li assert(TSK != TSK_ExplicitInstantiationDefinition &&
13481*67e74705SXin Li TSK != TSK_ImplicitInstantiation &&
13482*67e74705SXin Li "Instantiations don't have key functions");
13483*67e74705SXin Li (void)TSK;
13484*67e74705SXin Li } else if (!KeyFunction) {
13485*67e74705SXin Li // If we have a class with no key function that is the subject
13486*67e74705SXin Li // of an explicit instantiation declaration, suppress the
13487*67e74705SXin Li // vtable; it will live with the explicit instantiation
13488*67e74705SXin Li // definition.
13489*67e74705SXin Li bool IsExplicitInstantiationDeclaration
13490*67e74705SXin Li = Class->getTemplateSpecializationKind()
13491*67e74705SXin Li == TSK_ExplicitInstantiationDeclaration;
13492*67e74705SXin Li for (auto R : Class->redecls()) {
13493*67e74705SXin Li TemplateSpecializationKind TSK
13494*67e74705SXin Li = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13495*67e74705SXin Li if (TSK == TSK_ExplicitInstantiationDeclaration)
13496*67e74705SXin Li IsExplicitInstantiationDeclaration = true;
13497*67e74705SXin Li else if (TSK == TSK_ExplicitInstantiationDefinition) {
13498*67e74705SXin Li IsExplicitInstantiationDeclaration = false;
13499*67e74705SXin Li break;
13500*67e74705SXin Li }
13501*67e74705SXin Li }
13502*67e74705SXin Li
13503*67e74705SXin Li if (IsExplicitInstantiationDeclaration)
13504*67e74705SXin Li DefineVTable = false;
13505*67e74705SXin Li }
13506*67e74705SXin Li
13507*67e74705SXin Li // The exception specifications for all virtual members may be needed even
13508*67e74705SXin Li // if we are not providing an authoritative form of the vtable in this TU.
13509*67e74705SXin Li // We may choose to emit it available_externally anyway.
13510*67e74705SXin Li if (!DefineVTable) {
13511*67e74705SXin Li MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13512*67e74705SXin Li continue;
13513*67e74705SXin Li }
13514*67e74705SXin Li
13515*67e74705SXin Li // Mark all of the virtual members of this class as referenced, so
13516*67e74705SXin Li // that we can build a vtable. Then, tell the AST consumer that a
13517*67e74705SXin Li // vtable for this class is required.
13518*67e74705SXin Li DefinedAnything = true;
13519*67e74705SXin Li MarkVirtualMembersReferenced(Loc, Class);
13520*67e74705SXin Li CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13521*67e74705SXin Li if (VTablesUsed[Canonical])
13522*67e74705SXin Li Consumer.HandleVTable(Class);
13523*67e74705SXin Li
13524*67e74705SXin Li // Optionally warn if we're emitting a weak vtable.
13525*67e74705SXin Li if (Class->isExternallyVisible() &&
13526*67e74705SXin Li Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13527*67e74705SXin Li const FunctionDecl *KeyFunctionDef = nullptr;
13528*67e74705SXin Li if (!KeyFunction ||
13529*67e74705SXin Li (KeyFunction->hasBody(KeyFunctionDef) &&
13530*67e74705SXin Li KeyFunctionDef->isInlined()))
13531*67e74705SXin Li Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13532*67e74705SXin Li TSK_ExplicitInstantiationDefinition
13533*67e74705SXin Li ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13534*67e74705SXin Li << Class;
13535*67e74705SXin Li }
13536*67e74705SXin Li }
13537*67e74705SXin Li VTableUses.clear();
13538*67e74705SXin Li
13539*67e74705SXin Li return DefinedAnything;
13540*67e74705SXin Li }
13541*67e74705SXin Li
MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,const CXXRecordDecl * RD)13542*67e74705SXin Li void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13543*67e74705SXin Li const CXXRecordDecl *RD) {
13544*67e74705SXin Li for (const auto *I : RD->methods())
13545*67e74705SXin Li if (I->isVirtual() && !I->isPure())
13546*67e74705SXin Li ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13547*67e74705SXin Li }
13548*67e74705SXin Li
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD)13549*67e74705SXin Li void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13550*67e74705SXin Li const CXXRecordDecl *RD) {
13551*67e74705SXin Li // Mark all functions which will appear in RD's vtable as used.
13552*67e74705SXin Li CXXFinalOverriderMap FinalOverriders;
13553*67e74705SXin Li RD->getFinalOverriders(FinalOverriders);
13554*67e74705SXin Li for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13555*67e74705SXin Li E = FinalOverriders.end();
13556*67e74705SXin Li I != E; ++I) {
13557*67e74705SXin Li for (OverridingMethods::const_iterator OI = I->second.begin(),
13558*67e74705SXin Li OE = I->second.end();
13559*67e74705SXin Li OI != OE; ++OI) {
13560*67e74705SXin Li assert(OI->second.size() > 0 && "no final overrider");
13561*67e74705SXin Li CXXMethodDecl *Overrider = OI->second.front().Method;
13562*67e74705SXin Li
13563*67e74705SXin Li // C++ [basic.def.odr]p2:
13564*67e74705SXin Li // [...] A virtual member function is used if it is not pure. [...]
13565*67e74705SXin Li if (!Overrider->isPure())
13566*67e74705SXin Li MarkFunctionReferenced(Loc, Overrider);
13567*67e74705SXin Li }
13568*67e74705SXin Li }
13569*67e74705SXin Li
13570*67e74705SXin Li // Only classes that have virtual bases need a VTT.
13571*67e74705SXin Li if (RD->getNumVBases() == 0)
13572*67e74705SXin Li return;
13573*67e74705SXin Li
13574*67e74705SXin Li for (const auto &I : RD->bases()) {
13575*67e74705SXin Li const CXXRecordDecl *Base =
13576*67e74705SXin Li cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13577*67e74705SXin Li if (Base->getNumVBases() == 0)
13578*67e74705SXin Li continue;
13579*67e74705SXin Li MarkVirtualMembersReferenced(Loc, Base);
13580*67e74705SXin Li }
13581*67e74705SXin Li }
13582*67e74705SXin Li
13583*67e74705SXin Li /// SetIvarInitializers - This routine builds initialization ASTs for the
13584*67e74705SXin Li /// Objective-C implementation whose ivars need be initialized.
SetIvarInitializers(ObjCImplementationDecl * ObjCImplementation)13585*67e74705SXin Li void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13586*67e74705SXin Li if (!getLangOpts().CPlusPlus)
13587*67e74705SXin Li return;
13588*67e74705SXin Li if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13589*67e74705SXin Li SmallVector<ObjCIvarDecl*, 8> ivars;
13590*67e74705SXin Li CollectIvarsToConstructOrDestruct(OID, ivars);
13591*67e74705SXin Li if (ivars.empty())
13592*67e74705SXin Li return;
13593*67e74705SXin Li SmallVector<CXXCtorInitializer*, 32> AllToInit;
13594*67e74705SXin Li for (unsigned i = 0; i < ivars.size(); i++) {
13595*67e74705SXin Li FieldDecl *Field = ivars[i];
13596*67e74705SXin Li if (Field->isInvalidDecl())
13597*67e74705SXin Li continue;
13598*67e74705SXin Li
13599*67e74705SXin Li CXXCtorInitializer *Member;
13600*67e74705SXin Li InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13601*67e74705SXin Li InitializationKind InitKind =
13602*67e74705SXin Li InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13603*67e74705SXin Li
13604*67e74705SXin Li InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13605*67e74705SXin Li ExprResult MemberInit =
13606*67e74705SXin Li InitSeq.Perform(*this, InitEntity, InitKind, None);
13607*67e74705SXin Li MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13608*67e74705SXin Li // Note, MemberInit could actually come back empty if no initialization
13609*67e74705SXin Li // is required (e.g., because it would call a trivial default constructor)
13610*67e74705SXin Li if (!MemberInit.get() || MemberInit.isInvalid())
13611*67e74705SXin Li continue;
13612*67e74705SXin Li
13613*67e74705SXin Li Member =
13614*67e74705SXin Li new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13615*67e74705SXin Li SourceLocation(),
13616*67e74705SXin Li MemberInit.getAs<Expr>(),
13617*67e74705SXin Li SourceLocation());
13618*67e74705SXin Li AllToInit.push_back(Member);
13619*67e74705SXin Li
13620*67e74705SXin Li // Be sure that the destructor is accessible and is marked as referenced.
13621*67e74705SXin Li if (const RecordType *RecordTy =
13622*67e74705SXin Li Context.getBaseElementType(Field->getType())
13623*67e74705SXin Li ->getAs<RecordType>()) {
13624*67e74705SXin Li CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13625*67e74705SXin Li if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13626*67e74705SXin Li MarkFunctionReferenced(Field->getLocation(), Destructor);
13627*67e74705SXin Li CheckDestructorAccess(Field->getLocation(), Destructor,
13628*67e74705SXin Li PDiag(diag::err_access_dtor_ivar)
13629*67e74705SXin Li << Context.getBaseElementType(Field->getType()));
13630*67e74705SXin Li }
13631*67e74705SXin Li }
13632*67e74705SXin Li }
13633*67e74705SXin Li ObjCImplementation->setIvarInitializers(Context,
13634*67e74705SXin Li AllToInit.data(), AllToInit.size());
13635*67e74705SXin Li }
13636*67e74705SXin Li }
13637*67e74705SXin Li
13638*67e74705SXin Li static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallSet<CXXConstructorDecl *,4> & Valid,llvm::SmallSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallSet<CXXConstructorDecl *,4> & Current,Sema & S)13639*67e74705SXin Li void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13640*67e74705SXin Li llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13641*67e74705SXin Li llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13642*67e74705SXin Li llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13643*67e74705SXin Li Sema &S) {
13644*67e74705SXin Li if (Ctor->isInvalidDecl())
13645*67e74705SXin Li return;
13646*67e74705SXin Li
13647*67e74705SXin Li CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13648*67e74705SXin Li
13649*67e74705SXin Li // Target may not be determinable yet, for instance if this is a dependent
13650*67e74705SXin Li // call in an uninstantiated template.
13651*67e74705SXin Li if (Target) {
13652*67e74705SXin Li const FunctionDecl *FNTarget = nullptr;
13653*67e74705SXin Li (void)Target->hasBody(FNTarget);
13654*67e74705SXin Li Target = const_cast<CXXConstructorDecl*>(
13655*67e74705SXin Li cast_or_null<CXXConstructorDecl>(FNTarget));
13656*67e74705SXin Li }
13657*67e74705SXin Li
13658*67e74705SXin Li CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13659*67e74705SXin Li // Avoid dereferencing a null pointer here.
13660*67e74705SXin Li *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13661*67e74705SXin Li
13662*67e74705SXin Li if (!Current.insert(Canonical).second)
13663*67e74705SXin Li return;
13664*67e74705SXin Li
13665*67e74705SXin Li // We know that beyond here, we aren't chaining into a cycle.
13666*67e74705SXin Li if (!Target || !Target->isDelegatingConstructor() ||
13667*67e74705SXin Li Target->isInvalidDecl() || Valid.count(TCanonical)) {
13668*67e74705SXin Li Valid.insert(Current.begin(), Current.end());
13669*67e74705SXin Li Current.clear();
13670*67e74705SXin Li // We've hit a cycle.
13671*67e74705SXin Li } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13672*67e74705SXin Li Current.count(TCanonical)) {
13673*67e74705SXin Li // If we haven't diagnosed this cycle yet, do so now.
13674*67e74705SXin Li if (!Invalid.count(TCanonical)) {
13675*67e74705SXin Li S.Diag((*Ctor->init_begin())->getSourceLocation(),
13676*67e74705SXin Li diag::warn_delegating_ctor_cycle)
13677*67e74705SXin Li << Ctor;
13678*67e74705SXin Li
13679*67e74705SXin Li // Don't add a note for a function delegating directly to itself.
13680*67e74705SXin Li if (TCanonical != Canonical)
13681*67e74705SXin Li S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13682*67e74705SXin Li
13683*67e74705SXin Li CXXConstructorDecl *C = Target;
13684*67e74705SXin Li while (C->getCanonicalDecl() != Canonical) {
13685*67e74705SXin Li const FunctionDecl *FNTarget = nullptr;
13686*67e74705SXin Li (void)C->getTargetConstructor()->hasBody(FNTarget);
13687*67e74705SXin Li assert(FNTarget && "Ctor cycle through bodiless function");
13688*67e74705SXin Li
13689*67e74705SXin Li C = const_cast<CXXConstructorDecl*>(
13690*67e74705SXin Li cast<CXXConstructorDecl>(FNTarget));
13691*67e74705SXin Li S.Diag(C->getLocation(), diag::note_which_delegates_to);
13692*67e74705SXin Li }
13693*67e74705SXin Li }
13694*67e74705SXin Li
13695*67e74705SXin Li Invalid.insert(Current.begin(), Current.end());
13696*67e74705SXin Li Current.clear();
13697*67e74705SXin Li } else {
13698*67e74705SXin Li DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13699*67e74705SXin Li }
13700*67e74705SXin Li }
13701*67e74705SXin Li
13702*67e74705SXin Li
CheckDelegatingCtorCycles()13703*67e74705SXin Li void Sema::CheckDelegatingCtorCycles() {
13704*67e74705SXin Li llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13705*67e74705SXin Li
13706*67e74705SXin Li for (DelegatingCtorDeclsType::iterator
13707*67e74705SXin Li I = DelegatingCtorDecls.begin(ExternalSource),
13708*67e74705SXin Li E = DelegatingCtorDecls.end();
13709*67e74705SXin Li I != E; ++I)
13710*67e74705SXin Li DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13711*67e74705SXin Li
13712*67e74705SXin Li for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13713*67e74705SXin Li CE = Invalid.end();
13714*67e74705SXin Li CI != CE; ++CI)
13715*67e74705SXin Li (*CI)->setInvalidDecl();
13716*67e74705SXin Li }
13717*67e74705SXin Li
13718*67e74705SXin Li namespace {
13719*67e74705SXin Li /// \brief AST visitor that finds references to the 'this' expression.
13720*67e74705SXin Li class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13721*67e74705SXin Li Sema &S;
13722*67e74705SXin Li
13723*67e74705SXin Li public:
FindCXXThisExpr(Sema & S)13724*67e74705SXin Li explicit FindCXXThisExpr(Sema &S) : S(S) { }
13725*67e74705SXin Li
VisitCXXThisExpr(CXXThisExpr * E)13726*67e74705SXin Li bool VisitCXXThisExpr(CXXThisExpr *E) {
13727*67e74705SXin Li S.Diag(E->getLocation(), diag::err_this_static_member_func)
13728*67e74705SXin Li << E->isImplicit();
13729*67e74705SXin Li return false;
13730*67e74705SXin Li }
13731*67e74705SXin Li };
13732*67e74705SXin Li }
13733*67e74705SXin Li
checkThisInStaticMemberFunctionType(CXXMethodDecl * Method)13734*67e74705SXin Li bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13735*67e74705SXin Li TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13736*67e74705SXin Li if (!TSInfo)
13737*67e74705SXin Li return false;
13738*67e74705SXin Li
13739*67e74705SXin Li TypeLoc TL = TSInfo->getTypeLoc();
13740*67e74705SXin Li FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13741*67e74705SXin Li if (!ProtoTL)
13742*67e74705SXin Li return false;
13743*67e74705SXin Li
13744*67e74705SXin Li // C++11 [expr.prim.general]p3:
13745*67e74705SXin Li // [The expression this] shall not appear before the optional
13746*67e74705SXin Li // cv-qualifier-seq and it shall not appear within the declaration of a
13747*67e74705SXin Li // static member function (although its type and value category are defined
13748*67e74705SXin Li // within a static member function as they are within a non-static member
13749*67e74705SXin Li // function). [ Note: this is because declaration matching does not occur
13750*67e74705SXin Li // until the complete declarator is known. - end note ]
13751*67e74705SXin Li const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13752*67e74705SXin Li FindCXXThisExpr Finder(*this);
13753*67e74705SXin Li
13754*67e74705SXin Li // If the return type came after the cv-qualifier-seq, check it now.
13755*67e74705SXin Li if (Proto->hasTrailingReturn() &&
13756*67e74705SXin Li !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13757*67e74705SXin Li return true;
13758*67e74705SXin Li
13759*67e74705SXin Li // Check the exception specification.
13760*67e74705SXin Li if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13761*67e74705SXin Li return true;
13762*67e74705SXin Li
13763*67e74705SXin Li return checkThisInStaticMemberFunctionAttributes(Method);
13764*67e74705SXin Li }
13765*67e74705SXin Li
checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl * Method)13766*67e74705SXin Li bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13767*67e74705SXin Li TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13768*67e74705SXin Li if (!TSInfo)
13769*67e74705SXin Li return false;
13770*67e74705SXin Li
13771*67e74705SXin Li TypeLoc TL = TSInfo->getTypeLoc();
13772*67e74705SXin Li FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13773*67e74705SXin Li if (!ProtoTL)
13774*67e74705SXin Li return false;
13775*67e74705SXin Li
13776*67e74705SXin Li const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13777*67e74705SXin Li FindCXXThisExpr Finder(*this);
13778*67e74705SXin Li
13779*67e74705SXin Li switch (Proto->getExceptionSpecType()) {
13780*67e74705SXin Li case EST_Unparsed:
13781*67e74705SXin Li case EST_Uninstantiated:
13782*67e74705SXin Li case EST_Unevaluated:
13783*67e74705SXin Li case EST_BasicNoexcept:
13784*67e74705SXin Li case EST_DynamicNone:
13785*67e74705SXin Li case EST_MSAny:
13786*67e74705SXin Li case EST_None:
13787*67e74705SXin Li break;
13788*67e74705SXin Li
13789*67e74705SXin Li case EST_ComputedNoexcept:
13790*67e74705SXin Li if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13791*67e74705SXin Li return true;
13792*67e74705SXin Li
13793*67e74705SXin Li case EST_Dynamic:
13794*67e74705SXin Li for (const auto &E : Proto->exceptions()) {
13795*67e74705SXin Li if (!Finder.TraverseType(E))
13796*67e74705SXin Li return true;
13797*67e74705SXin Li }
13798*67e74705SXin Li break;
13799*67e74705SXin Li }
13800*67e74705SXin Li
13801*67e74705SXin Li return false;
13802*67e74705SXin Li }
13803*67e74705SXin Li
checkThisInStaticMemberFunctionAttributes(CXXMethodDecl * Method)13804*67e74705SXin Li bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13805*67e74705SXin Li FindCXXThisExpr Finder(*this);
13806*67e74705SXin Li
13807*67e74705SXin Li // Check attributes.
13808*67e74705SXin Li for (const auto *A : Method->attrs()) {
13809*67e74705SXin Li // FIXME: This should be emitted by tblgen.
13810*67e74705SXin Li Expr *Arg = nullptr;
13811*67e74705SXin Li ArrayRef<Expr *> Args;
13812*67e74705SXin Li if (const auto *G = dyn_cast<GuardedByAttr>(A))
13813*67e74705SXin Li Arg = G->getArg();
13814*67e74705SXin Li else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13815*67e74705SXin Li Arg = G->getArg();
13816*67e74705SXin Li else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13817*67e74705SXin Li Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13818*67e74705SXin Li else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13819*67e74705SXin Li Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13820*67e74705SXin Li else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13821*67e74705SXin Li Arg = ETLF->getSuccessValue();
13822*67e74705SXin Li Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13823*67e74705SXin Li } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13824*67e74705SXin Li Arg = STLF->getSuccessValue();
13825*67e74705SXin Li Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13826*67e74705SXin Li } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13827*67e74705SXin Li Arg = LR->getArg();
13828*67e74705SXin Li else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13829*67e74705SXin Li Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13830*67e74705SXin Li else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13831*67e74705SXin Li Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13832*67e74705SXin Li else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13833*67e74705SXin Li Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13834*67e74705SXin Li else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13835*67e74705SXin Li Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13836*67e74705SXin Li else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13837*67e74705SXin Li Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13838*67e74705SXin Li
13839*67e74705SXin Li if (Arg && !Finder.TraverseStmt(Arg))
13840*67e74705SXin Li return true;
13841*67e74705SXin Li
13842*67e74705SXin Li for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13843*67e74705SXin Li if (!Finder.TraverseStmt(Args[I]))
13844*67e74705SXin Li return true;
13845*67e74705SXin Li }
13846*67e74705SXin Li }
13847*67e74705SXin Li
13848*67e74705SXin Li return false;
13849*67e74705SXin Li }
13850*67e74705SXin Li
checkExceptionSpecification(bool IsTopLevel,ExceptionSpecificationType EST,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr,SmallVectorImpl<QualType> & Exceptions,FunctionProtoType::ExceptionSpecInfo & ESI)13851*67e74705SXin Li void Sema::checkExceptionSpecification(
13852*67e74705SXin Li bool IsTopLevel, ExceptionSpecificationType EST,
13853*67e74705SXin Li ArrayRef<ParsedType> DynamicExceptions,
13854*67e74705SXin Li ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13855*67e74705SXin Li SmallVectorImpl<QualType> &Exceptions,
13856*67e74705SXin Li FunctionProtoType::ExceptionSpecInfo &ESI) {
13857*67e74705SXin Li Exceptions.clear();
13858*67e74705SXin Li ESI.Type = EST;
13859*67e74705SXin Li if (EST == EST_Dynamic) {
13860*67e74705SXin Li Exceptions.reserve(DynamicExceptions.size());
13861*67e74705SXin Li for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13862*67e74705SXin Li // FIXME: Preserve type source info.
13863*67e74705SXin Li QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13864*67e74705SXin Li
13865*67e74705SXin Li if (IsTopLevel) {
13866*67e74705SXin Li SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13867*67e74705SXin Li collectUnexpandedParameterPacks(ET, Unexpanded);
13868*67e74705SXin Li if (!Unexpanded.empty()) {
13869*67e74705SXin Li DiagnoseUnexpandedParameterPacks(
13870*67e74705SXin Li DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13871*67e74705SXin Li Unexpanded);
13872*67e74705SXin Li continue;
13873*67e74705SXin Li }
13874*67e74705SXin Li }
13875*67e74705SXin Li
13876*67e74705SXin Li // Check that the type is valid for an exception spec, and
13877*67e74705SXin Li // drop it if not.
13878*67e74705SXin Li if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13879*67e74705SXin Li Exceptions.push_back(ET);
13880*67e74705SXin Li }
13881*67e74705SXin Li ESI.Exceptions = Exceptions;
13882*67e74705SXin Li return;
13883*67e74705SXin Li }
13884*67e74705SXin Li
13885*67e74705SXin Li if (EST == EST_ComputedNoexcept) {
13886*67e74705SXin Li // If an error occurred, there's no expression here.
13887*67e74705SXin Li if (NoexceptExpr) {
13888*67e74705SXin Li assert((NoexceptExpr->isTypeDependent() ||
13889*67e74705SXin Li NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13890*67e74705SXin Li Context.BoolTy) &&
13891*67e74705SXin Li "Parser should have made sure that the expression is boolean");
13892*67e74705SXin Li if (IsTopLevel && NoexceptExpr &&
13893*67e74705SXin Li DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13894*67e74705SXin Li ESI.Type = EST_BasicNoexcept;
13895*67e74705SXin Li return;
13896*67e74705SXin Li }
13897*67e74705SXin Li
13898*67e74705SXin Li if (!NoexceptExpr->isValueDependent())
13899*67e74705SXin Li NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13900*67e74705SXin Li diag::err_noexcept_needs_constant_expression,
13901*67e74705SXin Li /*AllowFold*/ false).get();
13902*67e74705SXin Li ESI.NoexceptExpr = NoexceptExpr;
13903*67e74705SXin Li }
13904*67e74705SXin Li return;
13905*67e74705SXin Li }
13906*67e74705SXin Li }
13907*67e74705SXin Li
actOnDelayedExceptionSpecification(Decl * MethodD,ExceptionSpecificationType EST,SourceRange SpecificationRange,ArrayRef<ParsedType> DynamicExceptions,ArrayRef<SourceRange> DynamicExceptionRanges,Expr * NoexceptExpr)13908*67e74705SXin Li void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13909*67e74705SXin Li ExceptionSpecificationType EST,
13910*67e74705SXin Li SourceRange SpecificationRange,
13911*67e74705SXin Li ArrayRef<ParsedType> DynamicExceptions,
13912*67e74705SXin Li ArrayRef<SourceRange> DynamicExceptionRanges,
13913*67e74705SXin Li Expr *NoexceptExpr) {
13914*67e74705SXin Li if (!MethodD)
13915*67e74705SXin Li return;
13916*67e74705SXin Li
13917*67e74705SXin Li // Dig out the method we're referring to.
13918*67e74705SXin Li if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13919*67e74705SXin Li MethodD = FunTmpl->getTemplatedDecl();
13920*67e74705SXin Li
13921*67e74705SXin Li CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13922*67e74705SXin Li if (!Method)
13923*67e74705SXin Li return;
13924*67e74705SXin Li
13925*67e74705SXin Li // Check the exception specification.
13926*67e74705SXin Li llvm::SmallVector<QualType, 4> Exceptions;
13927*67e74705SXin Li FunctionProtoType::ExceptionSpecInfo ESI;
13928*67e74705SXin Li checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13929*67e74705SXin Li DynamicExceptionRanges, NoexceptExpr, Exceptions,
13930*67e74705SXin Li ESI);
13931*67e74705SXin Li
13932*67e74705SXin Li // Update the exception specification on the function type.
13933*67e74705SXin Li Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13934*67e74705SXin Li
13935*67e74705SXin Li if (Method->isStatic())
13936*67e74705SXin Li checkThisInStaticMemberFunctionExceptionSpec(Method);
13937*67e74705SXin Li
13938*67e74705SXin Li if (Method->isVirtual()) {
13939*67e74705SXin Li // Check overrides, which we previously had to delay.
13940*67e74705SXin Li for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13941*67e74705SXin Li OEnd = Method->end_overridden_methods();
13942*67e74705SXin Li O != OEnd; ++O)
13943*67e74705SXin Li CheckOverridingFunctionExceptionSpec(Method, *O);
13944*67e74705SXin Li }
13945*67e74705SXin Li }
13946*67e74705SXin Li
13947*67e74705SXin Li /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13948*67e74705SXin Li ///
HandleMSProperty(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS,AttributeList * MSPropertyAttr)13949*67e74705SXin Li MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13950*67e74705SXin Li SourceLocation DeclStart,
13951*67e74705SXin Li Declarator &D, Expr *BitWidth,
13952*67e74705SXin Li InClassInitStyle InitStyle,
13953*67e74705SXin Li AccessSpecifier AS,
13954*67e74705SXin Li AttributeList *MSPropertyAttr) {
13955*67e74705SXin Li IdentifierInfo *II = D.getIdentifier();
13956*67e74705SXin Li if (!II) {
13957*67e74705SXin Li Diag(DeclStart, diag::err_anonymous_property);
13958*67e74705SXin Li return nullptr;
13959*67e74705SXin Li }
13960*67e74705SXin Li SourceLocation Loc = D.getIdentifierLoc();
13961*67e74705SXin Li
13962*67e74705SXin Li TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13963*67e74705SXin Li QualType T = TInfo->getType();
13964*67e74705SXin Li if (getLangOpts().CPlusPlus) {
13965*67e74705SXin Li CheckExtraCXXDefaultArguments(D);
13966*67e74705SXin Li
13967*67e74705SXin Li if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13968*67e74705SXin Li UPPC_DataMemberType)) {
13969*67e74705SXin Li D.setInvalidType();
13970*67e74705SXin Li T = Context.IntTy;
13971*67e74705SXin Li TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13972*67e74705SXin Li }
13973*67e74705SXin Li }
13974*67e74705SXin Li
13975*67e74705SXin Li DiagnoseFunctionSpecifiers(D.getDeclSpec());
13976*67e74705SXin Li
13977*67e74705SXin Li if (D.getDeclSpec().isInlineSpecified())
13978*67e74705SXin Li Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13979*67e74705SXin Li << getLangOpts().CPlusPlus1z;
13980*67e74705SXin Li if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13981*67e74705SXin Li Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13982*67e74705SXin Li diag::err_invalid_thread)
13983*67e74705SXin Li << DeclSpec::getSpecifierName(TSCS);
13984*67e74705SXin Li
13985*67e74705SXin Li // Check to see if this name was declared as a member previously
13986*67e74705SXin Li NamedDecl *PrevDecl = nullptr;
13987*67e74705SXin Li LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13988*67e74705SXin Li LookupName(Previous, S);
13989*67e74705SXin Li switch (Previous.getResultKind()) {
13990*67e74705SXin Li case LookupResult::Found:
13991*67e74705SXin Li case LookupResult::FoundUnresolvedValue:
13992*67e74705SXin Li PrevDecl = Previous.getAsSingle<NamedDecl>();
13993*67e74705SXin Li break;
13994*67e74705SXin Li
13995*67e74705SXin Li case LookupResult::FoundOverloaded:
13996*67e74705SXin Li PrevDecl = Previous.getRepresentativeDecl();
13997*67e74705SXin Li break;
13998*67e74705SXin Li
13999*67e74705SXin Li case LookupResult::NotFound:
14000*67e74705SXin Li case LookupResult::NotFoundInCurrentInstantiation:
14001*67e74705SXin Li case LookupResult::Ambiguous:
14002*67e74705SXin Li break;
14003*67e74705SXin Li }
14004*67e74705SXin Li
14005*67e74705SXin Li if (PrevDecl && PrevDecl->isTemplateParameter()) {
14006*67e74705SXin Li // Maybe we will complain about the shadowed template parameter.
14007*67e74705SXin Li DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14008*67e74705SXin Li // Just pretend that we didn't see the previous declaration.
14009*67e74705SXin Li PrevDecl = nullptr;
14010*67e74705SXin Li }
14011*67e74705SXin Li
14012*67e74705SXin Li if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14013*67e74705SXin Li PrevDecl = nullptr;
14014*67e74705SXin Li
14015*67e74705SXin Li SourceLocation TSSL = D.getLocStart();
14016*67e74705SXin Li const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14017*67e74705SXin Li MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14018*67e74705SXin Li Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14019*67e74705SXin Li ProcessDeclAttributes(TUScope, NewPD, D);
14020*67e74705SXin Li NewPD->setAccess(AS);
14021*67e74705SXin Li
14022*67e74705SXin Li if (NewPD->isInvalidDecl())
14023*67e74705SXin Li Record->setInvalidDecl();
14024*67e74705SXin Li
14025*67e74705SXin Li if (D.getDeclSpec().isModulePrivateSpecified())
14026*67e74705SXin Li NewPD->setModulePrivate();
14027*67e74705SXin Li
14028*67e74705SXin Li if (NewPD->isInvalidDecl() && PrevDecl) {
14029*67e74705SXin Li // Don't introduce NewFD into scope; there's already something
14030*67e74705SXin Li // with the same name in the same scope.
14031*67e74705SXin Li } else if (II) {
14032*67e74705SXin Li PushOnScopeChains(NewPD, S);
14033*67e74705SXin Li } else
14034*67e74705SXin Li Record->addDecl(NewPD);
14035*67e74705SXin Li
14036*67e74705SXin Li return NewPD;
14037*67e74705SXin Li }
14038